module DefaultWidgetHelper
  def get_field_header(field)
    I18n.t("#{@page_part.module_app.key}.default_widget.#{field}")
  end

  def link_to_field(row_data,field, switch, options=nil)
    method_ary = @page_part.module_app.widget_fields_link_method
    field = field.to_sym
    options = options || {}
    options[:clicked_field_name] = field
    if(method_ary.has_key?(field) and (switch.to_s == "true"))
      url = case method_ary[field][:args]
      when nil # no args
        get_data_link(method_ary[field][:method], options)
      when :self # passing self
        get_data_link(method_ary[field][:method], options,row_data.id)
      else 
        ary = method_ary[field][:args].clone
        object_hash = ary.each do |key,val|  
          ary[key]= type_trans_or_to_s(row_data.send(val[0]).send(val[1]))
        end
        get_data_link(method_ary[field][:method], options,object_hash)
      end

      link_to row_data.send(field), url
     else
      type_trans_or_to_s(row_data.send(field) )
    end
  end

  # def get_args_mapping(object,row_hash)
  #   first_hash = row_hash.first

  #   # row_data.send(method_ary[field]["args"])
  # end

  def type_trans_or_to_s(object)
    case object
      when Date
        display_date(object)
      when DateTime
        display_date_time(object)
      when String
        object
      else
        object.to_s      
    end
  end

  def get_data_link(method_entry, options=nil, object = nil)
    case object
    when NilClass
      eval eval("#{method_entry}(#{options})")
    when BSON::ObjectId
      object = object.to_s
      eval("#{method_entry}(#{{:id => object}.merge options})")
    when Hash
      eval("#{method_entry}(#{object.merge options})") 
    else
      ''
    end
  end

  def get_display(row_data,field_setting)
    label = row_data.send(field_setting[:method])
    type_trans_or_to_s(label)
  end

  def get_row_data(row_data,field)
    field_is_link = (field[0][1]== 'false' ?  false : true )
    field_setting = {:class=>field[0][1],:method=>field[0][0]}
    if  field_is_link
      field_link = field[0][1].to_s + '_path'
      link = link_to(get_display(row_data,field_setting),field_link.send(row_data))
      content_tag(:span,link,:class=>field_setting[:class])
    else
      content_tag(:span,get_display(row_data,field_setting),:class=>field_setting[:class])
    end
  end
end