module Users
  class ApplicationController < ::ApplicationController
    before_action :allow_all_origins
    before_action :user_authentication, unless: ->(c){ %w(obtain_token).include?(c.action_name) } # , except: [:obtain_token, :index]

    private

    def user_authentication
      if params[:auth_token].present?
        user = User.find_by_authentication_token(params[:auth_token])
        sign_in user if user
        sign_out current_user if current_user && !user # Other token attempt of logged in user
      elsif request.format.html?
        return if Rails.env.test? and action_name == 'index'
        authenticate_user!
      end

      unless current_user.present?
        respond_to do |format|
          format.html {redirect_to new_user_session_path}
          format.json {render json: json_response(ok: false, status: 401), status: :unauthorized}
        end
      end
    end

    def handle_message_params
      flash.now[:notice] = t('messages.the_list_has_been_closed', list: List.model_name.human) if params[:list_closed].present?
      flash.now[:notice] = t("messages.#{params[:message]}", list: List.model_name.human, supplier: Supplier.model_name.human) if params[:message].present? && params[:message] =~ /^\w+$/
    end

    # General handler of json responses. Will be able to set some additional communication data.
    # By default a response is ok.
    def json_response(obj = {})
      obj[:ok] = true unless obj.has_key?(:ok)
      obj
    end

    def new_order_product_orders
      case params[:product_orders]
      when String then JSON.parse(params[:product_orders]) rescue []
      when Hash then params[:product_orders].values
      else
        []
      end
    end
  end
end
