class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception


  def check_enabled
    if (!@current_customer and current_admin and params[:admin])
    
      
    elsif (@current_customer and !@current_customer.account_validated?) 
      redirect_to public_my_account_path
    end
  end

  def auth_customer

    session[:devise_id] = params[:d] if params[:d]
    if !current_customer and !(current_admin and params[:admin])
      session[:before_auth_url] = request.url
      redirect_to new_public_customers_auth_path(:p => params[:p], :for_annonce => (true if params[:controller] == "public/annonces"))
    else
      if !(current_admin and params[:admin])
        @current_customer.last_activity = DateTime.now
        @current_customer.save
      end
    end
  end

  private

  def auth_admin
    if !current_admin
      redirect_to new_admin_admin_auth_path
    end
  end

  private
  def current_admin
    if cookies[:admin_remember_token]
      if @current_admin = Admin.find_by_remember_token(cookies[:admin_remember_token])
        @current_admin = Admin.find_by_remember_token(cookies[:admin_remember_token])
      else
          cookies[:admin_remember_token] =nil
      end
    end
  end

  def current_customer
    if cookies[:customer_auth_token] and Customer.exists?(:token => cookies[:customer_auth_token])
      a_c = Customer.find_by_token(cookies[:customer_auth_token])
      if !a_c.lock
        @current_customer = a_c

      else
        cookies[:customer_auth_token] = nil
        nil
      end
    else
      nil
    end
  end

  def redirect_back_or_default(default = root_path, options = {})
    redirect_to (request.referer.present? ? :back : default), options
  end

  helper_method :current_admin, :current_customer

end