class ApplicationController < ActionController::Base
  before_action :set_locale
  if Rails.env.development?
    before_action :force_reloads
  end
  layout :layout_by_resource
  #before_action do
    #flash.now[:notice] = "Test notice"
    #flash.now[:alert] = "Test alert"
  #end
  #protect_from_forgery

  rescue_from SimplyStored::RecordNotFound, with: :show_404

private

  def authorize_cmtool
    redirect_to '/', alert: t('general.unauthorized') unless current_user.present? && current_user.admin?
  end

  def broadcast_user(uid, event, data = {})
    Qwaiter.broadcast_user uid, event, data
  end

  def broadcast_supplier(sid, event, data = {})
    Qwaiter.broadcast_supplier sid, event, data
  end

  def set_locale
    I18n.locale = (params[:locale].presence || I18n.default_locale).to_sym
  end

  def layout_by_resource(*args)
    #if devise_controller?
      #return 'obtain_token' if session[:user_return_to].present? # resource_name == :user ????
      #return 'theme1' if session[:supplier_return_to].present?
    #end
    "theme1"
  end

  def check_active_list_state
    if current_user.try(:active_list_id)
      unless active_list.active?
        current_user.list_is_closed!
        redirect_to user_root_path, alert: t('messages.the_list_has_been_closed', list: List.model_name.human)
      end
    end
  end

  def active_list
    return nil unless current_user.try(:active_list_id).present?
    @active_list ||= List.find(current_user.active_list_id)
  end
  alias :active_list_object :active_list
  helper_method :active_list_object

  def js_alert(*args)
    options = args.extract_options!
    message = args.first || ''
    {ok: false, message: message}.merge(options).to_json
  end
  alias json_alert js_alert
  def js_notice(*args)
    options = args.extract_options!
    message = args.first || ''
    {ok: true, message: message}.merge(options).to_json
  end
  alias json_notice js_notice

  def show_404
    respond_to do |format|
      format.html { render 'dashboard/404', layout: true, status: 404}
      format.json { render json: {ok: false}, status: 404 }
    end
  end

  def force_reloads
    load Rails.root.join('config/initializers/custom_form_builder.rb')
  end
end
