<commit_before>require 'will_paginate/array'
class Aichi11TargetDashboardSerializer < CountrySerializer
  PER_PAGE = 15.freeze
  STATS = {
    country: {
      id: 'country/region',
      name: 'Country/Region',
      column_name: 'name'
    },
    coverage: {
      id: 'coverage',
      name: 'Coverage',
      relation: 'country_statistic',
      column_name: 'percentage_pa_type_cover'
    },
    effectively_managed: {
      id: 'effectively_managed',
      name: 'Effectiveley managed',
      relation: 'pame_statistic',
      column_name: 'pame_percentage_pa_type_cover'
    },
    well_connected: {
      id: 'well_connected',
      name: 'Well connected',
      relation: 'country_statistic',
      column_name: 'percentage_well_connected',
    },
    importance: {
      id: 'importance',
      name: 'Areas of importance for biodiversity',
      relation: 'country_statistic',
      column_name: 'percentage_importance'
    }
  }.freeze

  def initialize(params={}, data = nil)
    super(params, data)
    @search_id, @search_type = sanitise_search_term
  end

  def serialize
    serialized_data = {
      page: page,
      per_page: per_page,
      items: [],
      total_entries: sorted.length
    }
    # Loop through records
    sorted_and_paginated.map do |record|
      url = "/#{record['obj_type']}/#{record['iso']}"
      hash = {
        title: record['name'],
        url: url,
        obj_type: record['obj_type'],
        stats: []
      }

      STATS.reject { |key, value| key == :country }.map do |stat_name, stat|
        hash[:stats] << body_stats(stat, stat_name, record)
      end
      serialized_data[:items] << hash.dup
    end
    serialized_data
  end

  def serialize_head
    head.to_json
  end

  def serialize_options
    @params[:sort_by] ||= 'name'
    @params[:order] ||= 'asc'
    sorted.map do |i|
      id = "#{i['id']}-#{i['obj_type']}"
      {
        id: id,
        name: i['name']
      }
    end
  end

  private

  def sorted
    obj_type = @search_type == 'id' ? "AND obj_type = 'country'" : ''
    search = @search_id.present? ? "WHERE #{@search_type} = #{@search_id} #{obj_type}" : ''
    query = "SELECT * FROM aichi11_target_dashboard_view #{search}"
    _data = ActiveRecord::Base.connection.execute(query)

    _data = _data.sort_by { |d| d[sort_by] }
    order.downcase == 'desc'? _data.reverse : _data
  end

  def sorted_and_paginated
    sorted.paginate(page: page, per_page: per_page)
  end

  def sort_by
    # Splitting by / for the country/region parameter
    _sort_by = @params[:sort_by] ? @params[:sort_by].split('/').first : ''
    sort_field_land = 'percentage_pa_land_cover'
    sort_field_marine = 'percentage_pa_marine_cover'
    case _sort_by
    when 'coverage'
      "(#{sort_field_land} + #{sort_field_marine})"
    when 'effectively_managed'
      "(pame_#{sort_field_land} + pame_#{sort_field_marine})"
    else
      if _sort_by.present? && STATS[_sort_by.to_sym].present?
        STATS[_sort_by.to_sym][:column_name]
      else
        super
      end
    end
  end

  def head
    STATS.map do |key, stat|<commit_msg>Add default ordering by region_id, type and name<commit_after>require 'will_paginate/array'
class Aichi11TargetDashboardSerializer < CountrySerializer
  PER_PAGE = 15.freeze
  STATS = {
    country: {
      id: 'country/region',
      name: 'Country/Region',
      column_name: 'name'
    },
    coverage: {
      id: 'coverage',
      name: 'Coverage',
      relation: 'country_statistic',
      column_name: 'percentage_pa_type_cover'
    },
    effectively_managed: {
      id: 'effectively_managed',
      name: 'Effectiveley managed',
      relation: 'pame_statistic',
      column_name: 'pame_percentage_pa_type_cover'
    },
    well_connected: {
      id: 'well_connected',
      name: 'Well connected',
      relation: 'country_statistic',
      column_name: 'percentage_well_connected',
    },
    importance: {
      id: 'importance',
      name: 'Areas of importance for biodiversity',
      relation: 'country_statistic',
      column_name: 'percentage_importance'
    }
  }.freeze

  def initialize(params={}, data = nil)
    super(params, data)
    @search_id, @search_type = sanitise_search_term
  end

  def serialize
    serialized_data = {
      page: page,
      per_page: per_page,
      items: [],
      total_entries: sorted.length
    }
    # Loop through records
    sorted_and_paginated.map do |record|
      url = "/#{record['obj_type']}/#{record['iso']}"
      hash = {
        title: record['name'],
        url: url,
        obj_type: record['obj_type'],
        stats: []
      }

      STATS.reject { |key, value| key == :country }.map do |stat_name, stat|
        hash[:stats] << body_stats(stat, stat_name, record)
      end
      serialized_data[:items] << hash.dup
    end
    serialized_data
  end

  def serialize_head
    head.to_json
  end

  def serialize_options
    @params[:sort_by] ||= 'name'
    @params[:order] ||= 'asc'
    sorted.map do |i|
      id = "#{i['id']}-#{i['obj_type']}"
      {
        id: id,
        name: i['name']
      }
    end
  end

  private

  def sorted
    obj_type = @search_type == 'id' ? "AND obj_type = 'country'" : ''
    default_order = 'ORDER BY region_id, obj_type DESC, name'
    search = @search_id.present? ? "WHERE #{@search_type} = #{@search_id} #{obj_type}" : ''
    query = "SELECT * FROM aichi11_target_dashboard_view #{search} #{default_order}"
    _data = ActiveRecord::Base.connection.execute(query)

    if @params[:sort_by].present?
      _data = _data.sort_by { |d| d[sort_by] }
      order.downcase == 'desc'? _data.reverse : _data
    else
      _data.to_a
    end
  end

  def sorted_and_paginated
    sorted.paginate(page: page, per_page: per_page)
  end

  def sort_by
    # Splitting by / because of the country/region parameter
    _sort_by = @params[:sort_by] ? @params[:sort_by].split('/').first : ''
    sort_field_land = 'percentage_pa_land_cover'
    sort_field_marine = 'percentage_pa_marine_cover'
    case _sort_by
    when 'coverage'
      "(#{sort_field_land} + #{sort_field_marine})"
    when 'effectively_managed'
      "(pame_#{sort_field_land} + pame_#{sort_field_marine})"
    else
      if _sort_by.present? && STATS[_sort_by.to_sym].present?
        STATS[_sort_by.to_sym][:column_name]
      else
        super
      end
    end
  end

  def head
    STATS.map do |key, stat|
{'fraction_non_alphanumeric': 0.12755979365327497, 'fraction_numerical': 0.0018758793184305144, 'mean_word_length': 2.8197014925373134, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2647956', 'n_tokens_mistral': 2200, 'n_tokens_neox': 2182, 'n_words': 446}