class LdapUsersController < ApplicationController
  unloadable
  before_filter :require_admin, :setup_auth_source

  def index
    @ldap_users = LdapUser.find(:all)
  end

  def new
    @ldap_user = LdapUser.new
    render :action => "edit"
  end

  def create
    @user = User.new(:language => Setting.default_language)
    @ldap_user = LdapUser.new
    @user.login = @ldap_user.login = params[:ldap_user][:login]

    if assign_params_and_save
      flash[:notice] = l(:notice_successful_create)

      if @user.save_without_validation
        @user.auth_source = nil # dummy
        Mailer.deliver_account_information(@user, @ldap_user.password) if params[:send_information]
      else
        flash[:error] = l(:error_failed_to_create_redmine_user)
      end

      redirect_to :action => 'index'
    else
      render :action => 'edit'
    end
  end

  def edit
    @ldap_user = LdapUser.find(params[:id])
  end

  def update
    @user = User.find_by_login(params[:id]) || User.new(:login => params[:id])
    @ldap_user = LdapUser.find(params[:id])

    if assign_params_and_save
      flash[:notice] = l(:notice_successful_update)
      if @ldap_user.admin? && !params[:ldap_user][:password].blank?
        flash[:warning] = l(:warning_need_to_restart)
      end
    
      if @user.save_without_validation
        @user.auth_source = nil # dummy
        Mailer.deliver_account_information(@user, @ldap_user.password) if params[:send_information] && !@ldap_user.password.blank?
      else
        flash[:error] = l(:error_failed_to_update_redmine_user)
      end

      redirect_to :action => 'edit', :id => @ldap_user.login
    else
      render :action => 'edit'
    end
  end

  def destroy
    @ldap_user = LdapUser.find(params[:id])
    @ldap_user.destroy unless @ldap_user.nil?
    redirect_to :action => 'index'
  end

  private
  def setup_auth_source
    setting = RedmineLeSetting.instance
    return render_403 if setting.use_external_ldap
    return render_404 unless @auth_source = LdapUser.auth_source = setting.auth_source
  end

  def assign_params_and_save
    h = params[:ldap_user]
    attrs = %w[firstname lastname mail]
    attrs.each {|attr|
      @user.send(attr+"=", @ldap_user.send(attr+"=", h[attr]))
    }
    @ldap_user.password = h[:password]
    @ldap_user.password_confirmation = h[:password_confirmation]

    unless @user.valid?
      @user.errors.each_error {|attr, error|
        if attrs.include?(attr) && @user.send(attr+"_changed?")
          @ldap_user.errors.add_to_base(error.full_message)
        end
      }
    end
    @user.auth_source ||= @auth_source

    RedmineLeSetting.transaction do
      @ldap_user.errors.empty? && @ldap_user.save
    end

    @ldap_user.errors.empty?
  end
end
