#
#= 子モデル対応コントローラー用モジュール
# Authors:: Sumiyo Yamamoto
# Copyright:: Copyright (C) OrbusNeich Medical K.K.  2010.
#--
# date        name                   note
# 2010.6.18   Sumiyo Yamamoto        新規作成
#-------------------------------------------------------------------------------
#++
module Comm::Module::Controller
  #= 子モデル対応コントローラー用モジュール
  #------------------------------------------------------------------------#++
  module Children
    def self.included(base)
      base.class_eval do
        before_filter :get_parent_id
        before_filter :get_table_params, :only => [:create_children]
        before_filter :edit_table_params, :only => [:create_child]
      end
    end

    #== 表示画面向け一覧表示（親ID指定）
    #-----------------------------------------------------------------#++
    def index_children
      hrs = find_children.ext_hashfy
      respond_to do |format|
        format.ext_json{
          render :json => hrs.to_ext_json(@table_name, nil)
        }
      end
    end

    #== 編集画面向け一覧表示（親ID指定）
    #-----------------------------------------------------------------#++
    def children
      hrs = find_children.only_hashfy
      respond_to do |format|
        format.ext_json{
          render :json => hrs.to_ext_json(@table_name, nil)
        }
      end
    end

    #== 登録（親ID指定）
    #-----------------------------------------------------------------#++
    def create_children
      begin
        parent = @parent_mcls.find(@parent_id)
        children = @mcls.create(JSON.parse(@table_params))
        eval("parent.#{@table_name}.replace(children)")
        
        result = true
        msg = ''
      rescue => e
        result = false
        msg = [EMJ0003+EMD0001, "#{self.class.to_s}", e.class.to_s, e.message].join("<br>")
        logger.error(e.backtrace)
      end
      # 返却
      render :json => Comm::Tool::Json.result_json(result, msg)
    end
    
  protected
    def get_parent_id
      @parent_id = params[:id].to_i
    end

    def edit_table_params
      @table_params = ActiveSupport::JSON.decode(@table_params)
      @table_params.each do |p|
        params[@parent_key] = @parent_id
      end
    end

    def find_children
      return @mcls.sassign(@parent_key, @parent_id).all
    end
  end
end
