class CPanelUser
  include Mongoid::Document
  include Mongoid::Timestamps
  include ActiveModel::SecurePassword

  field :email
  field :fullname
  field :address
  field :phone_number
  field :registered, type: Boolean, default: false
  field :password_digest, type: String
  field :confirmation_token, type: String 
  field :reset_token, type: String
  field :first_time_run, type: Boolean, default: true
  field :registered_site_ids, type: Array, default: []
  
  has_secure_password

  has_many :site_requests

  validates :email, uniqueness: true
  validates :password, :on => [:create], length: {:in => 8..20}

  def generate_confirmation_token
    self.confirmation_token = SecureRandom.hex(5)
    self.save
    ResetCPanelPasswordMailer.send_user_confirmation(self).deliver
  end

  def is_confirmed?
    self.confirmation_token.nil?
  end

  def name
    self.fullname.nil? ? self.email : self.fullname
  end

  def generate_reset_token
    self.reset_token = SecureRandom.hex(5)
    self.save
  end

  def registered_sites
    RegisteredSite.find(self.registered_site_ids) rescue []
  end

  def send_password_reset_email
    self.generate_reset_token
    ResetCPanelPasswordMailer.reset_user_password(self).deliver
  end

  def self.check_password_token(reset_token = nil)
    user = self.find_by(reset_token: reset_token) rescue nil
    token_status = user.present?
    if token_status
      true
    else
      false
    end
  end

  def update_password(password, password_confirmation)
    self.update_attributes(password: password, password_confirmation: password_confirmation, reset_token: nil, registered: true)
    self.save
  end

  def self.confirm_email(confirmation_token = nil)
    if confirmation_token
      user = self.find_by(confirmation_token: confirmation_token) rescue nil
      token_status = user.present?
      case token_status
      when true
        user.confirmation_token = nil
        user.save
        return {:success => "true", :id => user.id.to_s}
      when false
        return {:success => "false"}
      end
    else
        return {:success => "false"}
    end
  end

end