class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?
  before_action :set_current
  around_action :set_locale

  rescue_from ActionController::InvalidAuthenticityToken do |_|
    flash[:alert] = t("form_session_expired")
    respond_to do |format|
      format.html { redirect_to referer_path || root_path }
      format.js { js_refresh }
    end
  end

  protected

  def referer_path
    ActionController::Routing::Routes.recognize_path(request.headers["Referer"], method: :get) rescue nil
  end


  def js_refresh(opts = {})
    flash[:alert] = opts[:alert] if opts[:alert]
    flash[:notice] = opts[:notice] if opts[:notice]
    render :js => "window.location.reload()"
  end

  def configure_permitted_parameters
    # Permit the `subscribe_newsletter` parameter along with the other
    # sign up parameters.
    devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name, :activity_sector,
                                                       :company, :job_title, :address, :zip_code,
                                                       :city, :country_id, :email, :phone, :login,
                                                       :civility, :comment, :terms_of_service,
                                                       billing_informations_attributes: [:id, :billing_company, :siret, :billing_address, :billing_zip_code, :billing_city, :billing_country_id, :billing_email]])
  end

  def after_sign_in_path_for(user)
    if user.active? && authorized_user?(user)
      session[:service_name] = 'PixTech'
      session[:provider_word] = Pixtech.instance&.value_for('provider_word') || 'provider'
      session[:creator_word] = Pixtech.instance&.value_for('creator_word') || 'creator'
      main_app.root_path
    else
      sign_out(user)
      flash.delete(:notice)
      flash[:alert] = t('devise.failure.not_allowed')
      main_app.root_path
    end
  end

  def authorized_user?(user)
    return true if user.roles_mask == 1
    return false if Parameter.load('superadmin_only')
    return true if user.roles_mask == 8
    return false unless Parameter.load('billing')
    return true if user.roles_mask == 16
    return false unless Parameter.load('billing') == 'photographer'
    return true if user.roles_mask == 32
    return true if user.roles_mask == 128
    false
  end

  def set_current
    Current.user = current_user
    Current.host = request.host
  end

  def set_locale(&action)
    locale = locale_params || session[:locale] || I18n.default_locale
    I18n.with_locale(locale, &action)
  end

  def locale_params
    if params[:locale] && params[:locale].to_sym.in?(I18n.available_locales)
      session[:locale] = params[:locale]
    end
  end
end
