 class JamRuby::User

  EMAIL_TMPL_WELCOME = 'welcome_message'
  EMAIL_TMPL_WELCOME_BETA = 'welcome_betauser'
  EMAIL_TMPL_WELCOMES = [EMAIL_TMPL_WELCOME_BETA, EMAIL_TMPL_WELCOME]

  CONFIRM_URL = "http://www.jamkazam.com/confirm"  # we can't get request.host_with_port, so hard-code confirm url (with user override)

  attr_accessible :admin, :raw_password, :musician, :can_invite, :photo_url, :internet_service_provider, :session_settings, :confirm_url, :email_template # :invite_email

  def raw_password
    ''
  end

  def raw_password= pw
    unless pw.blank?
      # change_password(pw, pw)
      self.updating_password = true 
      self.password = pw
      self.password_confirmation = pw

      if au = self.admin_user
        au.update_attribute(:encrypted_password, self.password_digest)
      end
    end
  end

  def country
    @country = "United States"
  end

  def musician
    @musician = true
  end

  def confirm_url
    @signup_confirm_url ||= CONFIRM_URL
  end

  def confirm_url= url
    @signup_confirm_url = url
  end

  def email_template
    @signup_email_template ||= EMAIL_TMPL_WELCOME_BETA
  end

  def email_template= tmpl
    @signup_email_template = tmpl
  end

  def admin_user
    User.where(:email => self.email)[0]
  end

  after_create do
    self.update_attribute(:signup_token, SecureRandom.urlsafe_base64)
    url = confirm_url
    url.chomp!('/')

    # only supporting two welcome templates ATM
    if EMAIL_TMPL_WELCOMES.index(self.email_template).nil?
      self.email_template = EMAIL_TMPL_WELCOME
    end
   # UserMailer.send(self.email_template, self, "#{url}/#{self.signup_token}").deliver
  end

  after_save do
    logger.debug("*** after_save: #{self.admin_changed?}")
    if self.admin_changed?
      if self.admin
        if self.admin_user.nil?
          au = User.create(:email => self.email)
          au.update_attribute(:encrypted_password, self.password_digest)
        end
      else
        self.admin_user.try(:destroy)
      end
    end
  end

end
