# encoding: utf-8
#
# Redmine - project management software
# Copyright (C) 2006-2013  Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

module AccountHelper

  def email_activation_register(user, &block)
    token = Token.new(:user => user, :action => "register")
    if user.save and token.save
      UserStatus.create(:user_id => user.id, :changsets_count => 0, :watchers_count => 0)
      Mailer.run.register(token)
      #flash[:notice] = l(:notice_account_register_done)
      #render action: 'email_valid', locals: {:mail => user.mail}
    else
      yield if block_given?
    end
    user
  end

  def automatically_register(user, &block)
    # Automatic activation
    user.activate
    user.last_login_on = Time.now
    if user.save
      UserStatus.create(:user_id => user.id, :changsets_count => 0, :watchers_count => 0)
      #self.logged_user = user
      #flash[:notice] = l(:notice_account_activated)
      #redirect_to my_account_url
    else
      yield if block_given?
    end
    user
  end

  # 自动创建一个新用户，但是初始状态是锁定的
  def automatically_register_lock(user, &block)
    user.lock
    user.last_login_on = Time.now
    if user.save
      UserStatus.create(:user_id => user.id, :changsets_count => 0, :watchers_count => 0)
    else
      yield if block_given?
    end
    user
  end

  def administrator_manually__register(user, &block)
    if user.save
      UserStatus.create(:user_id => user.id ,:changsets_count => 0, :watchers_count => 0)
      # Sends an email to the administrators
      Mailer.run.account_activation_request(user)
      #account_pending
    else
      yield if block_given?
    end
    user
  end

end
