class ApplicationController < ActionController::Base
  include Pundit::Authorization
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  # protect_from_forgery with: :exception
  protect_from_forgery unless: -> { request.format.json? }
  # skip_before_action :verify_authenticity_token
  after_action :flash_to_http_header
  before_action :get_footer_tokens
  before_action :get_global_doodads

  if (Rails.env.development? || Rails.env.test?)
    after_action :verify_authorized, unless: -> { devise_controller? }
    # after_action :verify_policy_scoped, only: :index
    rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

    private

    def user_not_authorized(exception)
      policy_name = exception.policy.class.to_s.underscore
      # flash[:alert] = "#{policy_name}.#{exception.query}"
      # flash[:error] = t "#{policy_name}.#{exception.query}", scope: "pundit", default: :default
      flash[:alert] = "Unable to #{exception.query[0..-2]} #{policy_name.split("_")[0].capitalize}"
      redirect_to (request.referrer || root_path)
    end
  end

  def authenticate_user!(args = nil)
    current_user.present?
  end

  def current_user
    super || User.where(soft_token: soft_token).first_or_initialize
  end

  private

  def add_body_css_class(css_class)
    @body_css_classes ||= []
    @body_css_classes << css_class
  end

  def get_footer_tokens
    @footer_tokens = policy_scope(Token)
  end

  def get_global_doodads
    @global_doodads = policy_scope(Doodad).where(is_global: true)
  end

  def flash_to_http_header
    return unless request.xhr?
    return if flash.empty?
    response.headers['X-FlashMessages'] = flash.to_hash.to_json
    flash.discard  # don't want the flash to appear when you reload page
  end

  def soft_token
    session[:user_token] ||= SecureRandom.hex(8)
  end

end
