module EasyExtensions
  module FieldFormats

    class File < Redmine::FieldFormat::Unbounded
      add 'file'

      def label
        :label_attachment
      end

      def get_value_from_params(value)
        value
      end

      def edit_tag(view, tag_id, tag_name, custom_field_value, options={})
        cv = CustomValue.new
        if custom_field_value.value
          if custom_field_value.value.is_a?(Hash)
            cv.save_attachments(custom_field_value.value['attachments'])
          else
            cv = CustomValue.includes(:attachments).where(:attachments => {:id => custom_field_value.value.split('|')}).preload(:attachments).first
          end
        end

        view.render :partial => 'attachments/form', :locals => {:container => (cv || CustomValue.new), :tag_name => "#{tag_name}[attachments]", :show_attached => true}
      end

      def formatted_value(view, custom_field, value, customized=nil, html=false)
        s = ''

        if value.present? && custom_field.present?
          custom_value_object = custom_field.custom_values.where(:value => value).first

          if custom_value_object
            attachments = Attachment.where(container_id: custom_value_object.id)
            if html
              s = '<span class="custom-field-file">'
              attachments.each do |a|
                s << view.link_to_attachment(a, :download => true, :class => 'icon icon-attachment')
              end
              s << '</span>'
            else
              s = attachments.map(&:filename).join(', ')
            end
          end
        end
        s.html_safe
      end

    end

  end
end
