#
# リビジョン管理
# コントローラ用
# Comm::Const::Errorをincludeしてください
#
module Comm::Module::Controller::Revision
  attr_accessor :parent
  
  def self.included(base)
    base.class_eval do
      before_filter :set_parent, :only => [:create, :update, :linkage]
    end
  end
  
  # 元データに更新がないかどうかのチェック
  #  更新されている場合は例外を発生します
  #
  def check_parent_revision(parent=@parent)
    return unless parent_manageble?(parent)
    
    parent_class = eval("#{parent[:table].classify}")
    table_rev = parent_class.find(:first,
                                  :select => "rev_number",
                                  :conditions => ["id = ?", parent[:id]]).rev_number
    unless table_rev.to_i == parent[:rev].to_i
      raise EMJ0010 + EMD0014 + ' -> your rev: ' + parent[:rev].to_s + ' -> table rev: ' + table_rev.to_s
    end
  end
  
  # relテーブルに登録されているかどうかのチェック
  #  既に登録されている場合はLinkageExisting例外を発生しますので
  #  処理続行の場合はキャッチしてなんとかします
  #
  def check_rels(id, mcls=@mcls)
    return [] unless parent_manageble?
    rels = get_rels(id, mcls)
    unless rels.empty?
      raise LinkageExisting, WMJ0010 + WMD0010
    end
  end
  
  class LinkageExisting < StandardError
  end
  
  # 関連データ取得
  def get_rels(id, mcls=@mcls)
    rels = Rel.find(:all,
                    :select => "table_name, record_id",
                    :conditions => ["parent_table_name = ? and parent_record_id = ?",
                                     mcls.name.tableize, id])
    return rels
  end
  
  # 門前払いの条件
  def parent_manageble?(parent=@parent)
    if parent.empty? || (parent[:table].empty? && parent[:rev].empty? && parent[:id].empty?)
      false
    else
      true
    end
  end
  
  # リビジョンデータをインスタンス変数に
  def set_parent
    @parent = params[:parent] ? params[:parent] : {}
  end
end