class Employee < ApplicationRecord
  has_secure_password

  has_many :shit_sales
  validates_presence_of :name, :role
  validates_presence_of :password, :on => [:create]
  validates :emp_id, uniqueness: true, numericality: true, length: {in: 1..4}, allow_blank: true
  validates :password, numericality: true, length: {in: 3..9}, allow_blank: true

  def self.all_emp_except_waiter
     Employee.where('role!=?','waiter')
  end

  def self.collection
    Employee.select("id, name").map { |e| [e.name, e.id] }
  end

  def self.login(emp_id, password)
    user = Employee.find_by_emp_id(emp_id)
    if (user)
      #user.authenticate(password)

      if (user.authenticate(password))
        user.generate_token
        user.session_expiry = DateTime.now.utc + 30.minutes
        user.session_last_login = DateTime.now.utc
        user.save
        return user
      end
    end


    return nil

  end

  def self.authenticate_by_token(session_token)

    if (session_token)
      user = Employee.find_by_token_session(session_token)
      if user && user.session_expiry.utc > DateTime.now.utc
        #Extend the login time each time authenticatation take place
        user.session_expiry = user.session_expiry.utc + 30.minutes
        user.save
        return true
      else
        return false
      end
    end

    return false
  end

  def self.logout(session_token)
    if (session_token)
      user = Employee.find_by_token_session(session_token)
      if user
        user.token_session = nil
        user.session_expiry = nil
        user.save
      end
    end
  end

  def generate_token
      update_column :token_session, SecureRandom.hex(10)
    rescue ActiveRecord::RecordNotUnique
      retry
  end


end
