# frozen_string_literal: true

class UxToolkitLogFilesController < ApplicationController
  layout 'admin'

  before_action :require_admin

  def index
    @line_counts = RedmineUxToolkit::Services::LogFiles::SUPPORTED_LINE_COUNTS
    @line_count = log_service.normalize_line_count(params[:lines])
    @log_files = log_service.log_files
    @selected_log_file = log_service.selected_file(params[:file])
    @log_content = @selected_log_file ? log_service.tail(@selected_log_file.name, @line_count) : ''
  rescue RedmineUxToolkit::Services::LogFiles::AccessDenied
    @log_error = l(:error_ux_toolkit_log_file_access_denied)
  rescue RedmineUxToolkit::Services::LogFiles::NotFound
    @log_error = l(:error_ux_toolkit_log_file_not_found)
  rescue RedmineUxToolkit::Services::LogFiles::NotReadable
    @log_error = l(:error_ux_toolkit_log_file_not_readable)
  end

  def flush
    line_count = log_service.normalize_line_count(params[:lines])
    log_file = log_service.selected_file(params[:file])

    log_service.flush(log_file.name)
    flash[:notice] = l(:notice_ux_toolkit_log_file_flushed)
    redirect_to ux_toolkit_log_files_path(file: log_file.name, lines: line_count)
  rescue RedmineUxToolkit::Services::LogFiles::AccessDenied
    flash[:error] = l(:error_ux_toolkit_log_file_access_denied)
    redirect_to ux_toolkit_log_files_path
  rescue RedmineUxToolkit::Services::LogFiles::NotFound
    flash[:error] = l(:error_ux_toolkit_log_file_not_found)
    redirect_to ux_toolkit_log_files_path
  rescue RedmineUxToolkit::Services::LogFiles::NotReadable
    flash[:error] = l(:error_ux_toolkit_log_file_not_readable)
    redirect_to ux_toolkit_log_files_path
  rescue RedmineUxToolkit::Services::LogFiles::NotWritable
    flash[:error] = l(:error_ux_toolkit_log_file_not_writable)
    redirect_to ux_toolkit_log_files_path(file: params[:file], lines: params[:lines])
  end

  private

  def log_service
    @log_service ||= RedmineUxToolkit::Services::LogFiles.new
  end
end
