class EpmChartQuery < EpmEasyQueryBase

  def category_name
    'charts'
  end

  def edit_path
    'easy_page_modules/charts/chart_query_edit'
  end

  def get_query_class(settings)
    settings['easy_query_type'].safe_constantize if settings['easy_query_type']
  end

  def output(settings)
    'chart'
  end

  def show_preview?
    false
  end

  def primary_renderer(settings, **options)
    (settings['chart_settings'] && settings['chart_settings']['primary_renderer']) || 'bar'
  end

  def get_edit_data(settings, user, page_context = {})
    additional_queries = {}
    settings['chart_settings'] ||= {}
    settings['chart_settings']['additional_queries'].each do |key, query_settings|
      q_cls = query_settings['easy_query_type'].constantize rescue nil
      next unless q_cls
      q = q_cls.new
      q.from_params(query_settings)
      q.project = page_context[:project] if page_context[:project]
      q.output = output(query_settings) || 'chart'
      q.export_formats = {}
      additional_queries[key] = q
    end if settings['chart_settings']['additional_queries'].is_a?(Hash)
    super.merge(additional_queries: additional_queries)
  end

  def get_query(settings, user, page_context={})
    set_primary_renderer(settings)
    settings['query_name'] ||= (get_query_class(settings) ? get_query_class(settings).translated_name + ' - ' : '') + translated_name
    query = super

    # Prepend additionals filters
    # Filters will be applied in chart output
    if query && page_context['global_filters'].is_a?(Hash) &&
                settings['chart_settings'] &&
                settings['chart_settings']['additional_queries'].is_a?(Hash)
      page_context['global_filters'].each do |key, query_settings|
        additional_query_settings = settings['chart_settings']['additional_queries'][key]
        next if additional_query_settings.nil?

        additional_query_settings['additional_filters'] = query_settings
      end
    end

    query
  end

  def set_primary_renderer(settings)
    settings['chart_settings'] ||= {}
    settings['chart_settings']['primary_renderer'] = primary_renderer(settings)
  end

  # Get used queries without applied filters
  # Return Hash where key is query prefix (because of multiple queries)
  def get_all_clean_queries(settings, user, page_context={})
    result = super

    if !settings['chart_settings'] || !settings['chart_settings']['additional_queries'].is_a?(Hash)
      return result
    end

    settings['chart_settings']['additional_queries'].each do |key, query_settings|
      query = query_settings['easy_query_type'].constantize rescue nil
      next unless query

      query = query.new
      query.project = page_context[:project] if page_context[:project]

      result[key] = query
    end

    result
  end

end
