module EasyPatch
  module ListFormatPatch

    def self.included(base)
      base.send(:include, InstanceMethods)

      base.class_eval do

        alias_method_chain :join_for_order_statement, :easy_extensions
        alias_method_chain :edit_tag, :easy_extensions

        self.type_for_inline_edit = ->(custom_field_value) {
          custom_field_value.custom_field.multiple ? 'checklist' : 'select'
        }

      end
    end

    module InstanceMethods

      def source_values_for_inline_edit(custom_field_value)
        possible_values_options(custom_field_value.custom_field).map do |possible_value|
          v = Array.wrap(possible_value)
          { text: v.first, value: v.last }
        end
      end

      def join_for_order_statement_with_easy_extensions(custom_field, uniq=true)
        alias_name = join_alias(custom_field)

        result = "LEFT OUTER JOIN #{CustomValue.table_name} #{alias_name}" +
          " ON #{alias_name}.customized_type = '#{custom_field.class.customized_class.base_class.name}'" +
          " AND #{alias_name}.customized_id = #{custom_field.class.customized_class.table_name}.id" +
          " AND #{alias_name}.custom_field_id = #{custom_field.id}" +
          " AND (#{custom_field.visibility_by_project_condition})" +
          " AND #{alias_name}.value <> ''"
        if uniq
          result += " AND #{alias_name}.id = (SELECT max(#{alias_name}_2.id) FROM #{CustomValue.table_name} #{alias_name}_2" +
            " WHERE #{alias_name}_2.customized_type = #{alias_name}.customized_type" +
            " AND #{alias_name}_2.customized_id = #{alias_name}.customized_id" +
            " AND #{alias_name}_2.custom_field_id = #{alias_name}.custom_field_id)"
        end
        result
      end

      def edit_tag_with_easy_extensions(view, tag_id, tag_name, custom_value, options={})
        if custom_value.custom_field.edit_tag_style == 'autocomplete'
          view.autocomplete_field_tag(tag_name, possible_custom_value_options(custom_value), custom_value.value, {:id => tag_id}.merge(options))
        else
          edit_tag_without_easy_extensions(view, tag_id, tag_name, custom_value, options)
        end
      end

    end

  end
end
