class EntriesController < ApplicationController
  before_action :set_entry, only: [ :show ]

  def index
    @supported_languages = SupportedLanguage.where(active: true).order(:sort_order, :name)
    @language_code = params[:language].presence
    @category = params[:category].presence
    @query = params[:q].to_s.strip
    @starts_with = params[:starts_with].presence
    @page = [ params[:page].to_i, 1 ].max
    @per_page = 25

    entries_scope = Entry.all
    entries_scope = entries_scope.with_category(@category)
    entries_scope = entries_scope.search(@query, language_code: @language_code)
    entries_scope = entries_scope.starts_with(@starts_with, language_code: @language_code) if @starts_with.present?
    entries_scope = entries_scope.alphabetical_for(@language_code) if @query.blank? && @starts_with.blank? && @language_code.present?
    entries_scope = entries_scope.order(created_at: :desc) if entries_scope.order_values.empty?

    @total_entries = entries_scope.count
    @total_pages = (@total_entries.to_f / @per_page).ceil
    @entries = entries_scope.offset((@page - 1) * @per_page).limit(@per_page)

    @entry_count = Entry.count
    @verified_count = Entry.where(verified: true).count
    @needs_review_count = @entry_count - @verified_count
    @complete_entries_count = @supported_languages.reduce(Entry.all) do |scope, language|
      scope.where.not(language.code => [ nil, "" ])
    end.count
    @missing_entries_count = @entry_count - @complete_entries_count
    @language_completion = @supported_languages.index_with do |language|
      next 0 if @entry_count.zero?

      (Entry.where.not(language.code => [ nil, "" ]).count * 100.0 / @entry_count).round
    end

    if @language_code.present?
      primary_language, other_languages = @supported_languages.partition { |language| language.code == @language_code }
      @display_languages = primary_language + other_languages
    else
      @display_languages = @supported_languages
    end

    respond_to do |format|
      format.html
      format.turbo_stream
    end
  end

  def show
    @supported_languages = SupportedLanguage.where(active: true).order(:sort_order, :name)
  end

  def download
    @entries = Entry.order(:id)
    respond_to do |format|
      format.xlsx do
        filename = "sanasto-entries-#{Time.zone.today}.xlsx"
        response.headers["Content-Disposition"] = "attachment; filename=\"#{filename}\""
      end
    end
  end

  private

  def set_entry
    @entry = Entry.find(params[:id])
  end
end
