require 'gollum-lib'


class WikiPage < ApplicationRecord
  belongs_to :tag, optional: true
  belongs_to :created_user, class_name: 'User', foreign_key: 'created_user_id'
  belongs_to :updated_user, class_name: 'User', foreign_key: 'updated_user_id'

  validates :title, presence: true, length: { maximum: 255 }, uniqueness: true

  def as_json options = { }
    self.sha = nil
    super options
  end

  def sha= val
    if val.present?
      @sha = val
      @page = wiki.page("#{ id }.md", @sha)
    else
      @page = wiki.page("#{ id }.md")
      @sha = @page.versions.first.id
    end
    vers = @page.versions
    idx = vers.find_index { |ver| ver.id == @sha }
    if idx
      @pred = vers[idx + 1]&.id
      @succ = idx.positive? ? vers[idx - 1].id : nil
      @updated_at = vers[idx].authored_date
    else
      @sha = nil
      @pred = nil
      @succ = nil
      @updated_at = nil
    end
    @sha
  end

  def sha
    @sha
  end

  def pred
    @pred
  end

  def succ
    @succ
  end

  def updated_at
    @updated_at
  end

  def body
    sha = nil unless @page
    @page&.raw_data&.force_encoding('UTF-8')
  end

  def set_body content, user:
    commit_info = { name:   user.id.to_s,
                    email:  'dummy@example.com' }
    page = wiki.page("#{ id }.md")
    if page
      commit_info[:message] = "Updated #{ id }"
      wiki.update_page(page, id.to_s, :markdown, content, commit_info)
    else
      commit_info[:message] = "Created #{ id }"
      wiki.write_page(id.to_s, :markdown, content, commit_info)
    end
  end

  private

  WIKI_PATH = Rails.root.join('wiki').to_s

  def wiki
    @wiki ||= Gollum::Wiki.new(WIKI_PATH)
  end
end
