require 'recaptcha'
class UserManager < BaseManager

  include Recaptcha::Verify
  
  def initialize(options={})
    super(options)
    @log = Logging.logger[self]
  end

  # Note that almost everything can be nil here. This is because when users sign up via social media,
  # we don't know much about them.
  def signup(remote_ip, first_name, last_name, email, password = nil, password_confirmation = nil, terms_of_service = nil, subscribe_email = nil,
             instruments = nil, birth_date = nil, location = nil, musician = nil, photo_url = nil, invited_user = nil, signup_confirm_url = nil)

    @user = User.new

    # check if we have disabled open signup for this site.   open == invited users can still get in
    if !SampleApp::Application.config.signup_enabled  && invited_user.nil?
      raise PermissionError, "Signups are currently disabled"
    end

    # a user should be able to specify their location, but if they don't, we'll best effort it
    if location.nil?
      location = MaxMindManager.lookup(remote_ip)
    end

    # TODO: figure out why can't user verify_recaptcha here
    # ALSO: make sure we dont do the recaptcha stuff if used facebook.

    # check recaptcha; if any errors seen, contribute it to the model
    #unless verify_recaptcha(:model => @user, :message => "recaptcha")
    #  return @user # @user.errors.any? is true now
    #else
    # sends email to email account for confirmation
    @user = User.signup(first_name, last_name, email, password, password_confirmation, terms_of_service, subscribe_email,
                        location, instruments, birth_date, musician, photo_url, invited_user, signup_confirm_url)

    return @user
    #end
  end

  def signup_confirm(signup_token, remote_ip=nil)
    begin
      @user = User.signup_confirm(signup_token)
      @user.location = MaxMindManager.lookup(remote_ip) if remote_ip
    rescue ActiveRecord::RecordNotFound
      @user = nil
    end

    return @user
  end

end
