class SessionsController < Devise::SessionsController
  protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }
  skip_before_action :verify_authenticity_token, only: :create, if: Proc.new {|c| c.request.format.json?}

  def after_sign_in_path_for(resource)
    #super admin redirection
    request.env['omniauth.origin'] || stored_location_for(resource) || root_path
  end

  def destroy
    redirect_path = after_sign_out_path_for(resource_name)
    if current_user.present?
    	PublicActivity::Activity.create(trackable_id: current_user.id, trackable_type: "User", owner_id: current_user.id, owner_type: "User", key: "user.logout", organisation_id: current_user.organisation_id, location_network_id: current_user.location_networks.present? ? current_user.location_networks.first.id : nil, parameters: {:attributes => {"user(#{current_user.email})" => {}}}, assumed_by: session[:assume_user])
    end
    signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name))
    set_flash_message :notice, :signed_out if signed_out && is_flashing_format?
    yield resource if block_given?

    # We actually need to hardcode this as Rails default responder doesn't
    # support returning empty response on GET request
    respond_to do |format|
      format.any(*navigational_formats) { redirect_to redirect_path }
    end
  end


  def create
    if request.format.symbol == :html
      super
    else
      @result = {}
      @user = User.find_for_database_authentication(:email=>params["email"])
      if @user.present? && @user.valid_password?(params["password"])
        @result["email"] = @user.email
        @result["access_token"] = @user.access_token unless @user.access_token.nil?
        @result["organisation_id"] = @user.organisation_id
        @result["organisation_name"] = @user.organisation.organisation_name
        @res_message = "You have successfully signed in"
        @res_status = 200
        #render json: {status: @res_status, message: @res_message, data: @result}
      else
        @res_message = "Invalid email or password"
        @res_status = 401
      end
        render json: {status: @res_status, message: @res_message, data: @result}
    end
  end
end
