module EasyConcerns
  module EasyPageTabs
    extend ActiveSupport::Concern

    included do
      helper_method :available_filters_types
    end

    private

      def available_filters_types
        {
          date_period: { name: l(:label_date) },
          country_select: { name: l(:label_country) },
          cf_list: { name: l(:label_list), manual_possible_values: true }
        }
      end

      def modules_filters_options(modules)
        # { module_uuid => { query_key => { filter_type => [*allowed_attributes] } } }
        options = {}

        modules.each do |mod|
          queries_settings = options[mod.uuid] = {}

          queries = mod.module_definition.get_all_clean_queries(mod.settings, User.current)
          queries.each do |key, query|

            query_settings = queries_settings[key] = {}
            query.available_filters.each do |attribute, filter_options|
              filter_type = filter_options[:type]

              if filter_type == :date_period
                query_settings[:date_period] ||= []
                query_settings[:date_period] << [filter_options[:name], attribute]
              elsif filter_type == :country_select
                query_settings[:country_select] ||= []
                query_settings[:country_select] << [filter_options[:name], attribute]
              elsif filter_options[:field]
                case filter_options[:field].field_format
                when 'country_select'
                  query_settings[:country_select] ||= []
                  query_settings[:country_select] << [filter_options[:name], attribute]
                when 'list'
                  query_settings[:cf_list] ||= []
                  query_settings[:cf_list] << [filter_options[:name], attribute]
                end
              end
            end

          end
        end

        options
      end

      def parse_filters_settings_from_params
        filters_settings = params.fetch(:filters_settings, {}).values
        filters_settings.each do |filter_settings|
          # Add filter identificator, important for applying a filter
          filter_settings['uuid'] = SecureRandom.uuid

          # Delete empty values
          Array(filter_settings['modules']).each do |uuid, module_settings|
            module_settings.keep_if {|_, attribute| attribute.present? }
          end
        end
        filters_settings
      end

  end
end
