class Client
  include Mongoid::Document
  field :site_name, type: String
  field :site_token, type: String
  field :site_id, type: String
  field :university, type: String
  field :department, type: String
  field :email, type: String
  field :country, type: String
  field :url, type: String
  field :confirmation_token, type: String

  index({ confirmation_token: 1}, { unique: true })

  validates :site_token, :uniqueness => true
  
  def generate_confirmation_token
      self.confirmation_token = SecureRandom.hex(5)
      self.save
  end

  def send_confirmation_email
    self.generate_confirmation_token
    ConfirmAdminMailer.admin_confirmation_email(self).deliver
  end

  def self.send_reconformation_email(email)
    client = self.find_by(email: email) rescue nil
    client_status = (client.present? && client.confirmation_token.present?)
    case client_status
    when true
      client.send_confirmation_email
      return[{:success => "true"}]
    when false
      return [{:success => "false"}]
    end
  end

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