require 'digest'

module Tools
  class TranslatorController < Tools::BaseController
    def show
      authorize Translator

      query_params = request.query_parameters || {}

      @translation ||= Translator.new

      translate unless query_params[:text].blank?
    end

    def translate
      authorize Translator

      @translation = Translator.from_params(params)

      unless @translation.valid?
        flash.now[:error] = @translation.errors.full_messages.to_sentence
      end

      render :show

      track_action! trackable_request
        .assemble_an
        .admin_panel_translate_text(
          source_text_language: @translation.from,
          output_text_language: @translation.to,
          source_text_length: @translation.text.length,
          source_text_hash: Digest::SHA256.hexdigest(@translation.text)
        )

      return
    end
  end
end
