require "application_responder"

class ApplicationController < ActionController::Base
  include Shared::Errors
  self.responder = ApplicationResponder
  respond_to :html, :json

  before_action :set_runtime_variables
  before_action :store_current_location, :unless => :devise_controller?
  protect_from_forgery with: :exception

  unless Rails.env.development?
    rescue_from ActionController::MissingFile, with: :render_res_error
    rescue_from Shared::Errors::ProcessError, with: :render_proc_error
    rescue_from ActiveRecord::RecordNotFound, with: :render_res_error
    rescue_from CanCan::AccessDenied, with: :render_cancan_error
    rescue_from ActionController::ParameterMissing, with: -> (e) { render_error(status: 400, message: e.message) }
  end

  private
  def _log(level, msg)
    logger.public_send level, "#{msg} (addr: #{request.remote_ip}, ua: #{request.user_agent})"
  end

  def set_runtime_variables
    conf = Rails.application.config
    Time.zone = conf.time_zone || 'UTC'
    I18n.locale = conf.i18n.default_locale
    if current_user
      current_user.timezone and
        Time.zone = current_user.timezone
      current_user.lang && conf.i18n.available_locales.member?(current_user.lang.to_sym) and
        I18n.locale = current_user.lang.to_sym
    elsif ua_locale = request.env['HTTP_ACCEPT_LANGUAGE'].to_s.scan(/^[a-z]{2}/).first
      conf.i18n.available_locales.member?(ua_locale.to_sym) and
        I18n.locale = ua_locale.to_sym
    end
    controller_name.start_with?('rails_admin/') and
      I18n.locale = :en
    true
  end

  # https://github.com/plataformatec/devise/wiki/How-To:-Redirect-back-to-current-page-after-sign-in,-sign-out,-sign-up,-update
  def after_sign_out_path_for(resource)
    request.referrer || root_path
  end

  def store_current_location
    store_location_for(:user, request.url)
  end

  def gen_ip_hash
    Digest::SHA1.hexdigest [Time.now.strftime('%U'),
                            request.remote_ip,
                            Rails.application.config.secret_key_base,
                           ].join("/")
  end
end
