module Poligloto
  class ApplicationController < ActionController::Base
    before_filter :authenticate_poligloto_user, if: lambda { Poligloto.uses_authentication? }
    before_filter :authorize_translator, if: lambda { Poligloto.uses_authentication? }
    before_filter :set_locale
    http_basic_authenticate_with name: Poligloto.basic_auth_user, password: Poligloto.basic_auth_password, if: lambda { !Rails.env.test? && !Poligloto.uses_authentication? }

    protected
      def set_locale
        I18n.locale = I18n.available_locales.detect { |locale| locale.to_s == params[:loc] } || I18n.default_locale
      end

      def authenticate_poligloto_user
        unless Poligloto.poligloto_user_signed_in?
          flash.alert = t('poligloto.application_controller.not_signed_in')
          return redirect_to Poligloto.sign_in_path
        end
      end

      def authorize_translator
        flash.alert = t('poligloto.application_controller.not_translator')
        return redirect_to main_app.root_url unless Poligloto.poligloto_user.is_translator?
      end
  end
end
