class ApplicationController < ActionController::Base
  include ControllerAfterAuthenticationHooks
  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 allow_all_origins
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Request-Method'] = '*'
    headers['Access-Control-Allow-Headers'] = '*'
    headers['Access-Control-Allow-Methods'] = '*'
  end

  #START CMTOOL
  def authorize_cmtool
    redirect_to main_app.new_administrator_session_path, alert: t('devise.failure.unauthenticated') unless current_administrator.present?
  end

  def cmtool_user
    current_administrator
  end

  def cmtool_locale
    :en
  end

  def go_to_page_path(record, locale: I18n.locale)
    case record
    when Page
      str = record.name
      locale = record.locale
    else
      str = record
    end
    locale ||= I18n.locale
    main_app.page_path(str, locale: locale)
  end
  helper_method :go_to_page_path
  #END CMTOOL

  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
    #session[:locale] = (params[:locale].presence || session[:locale] || Rails.configuration.i18n.default_locale).to_sym
    I18n.locale = params[:locale].presence.try(:to_sym) || Rails.configuration.i18n.default_locale
  end

  def _render_with_renderer_json(resource, options)
    return super if resource.is_a?(Hash) or resource.is_a?(String)
    options[:serializer] ||= begin
      if resource.is_a?(SimplyStored::Couch)
        #infer based on controller path replacing actual controller part with resouce part /lists/:id/table
        "#{self.class.name.deconstantize}::#{resource.class.name.demodulize}Serializer".constantize
      else
        # infer based on controller path
        "#{controller_path.classify}Serializer".constantize
      end
    end
    unless options.has_key?(:is_collection)
      options[:is_collection] = params[:id].blank? && %w[new create].exclude?(action_name)
    end
    JSONAPI::Serializer.serialize(resource, options).to_json
  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 after_sign_in_path_for(resource)
    case resource
    when Employee then supplier_root_path
    when Administrator then cmtool.root_path
    else root_path
    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
