class SessionsController < Devise::SessionsController
  prepend_before_filter :require_no_authentication, :only => [ :new, :create ]
  include Devise::Controllers::InternalHelpers


  # POST /resource/sign_in
  def create 
    # login_password = params[:user][:password]
    # login_uid = params[:user][:nccu_ldap_uid]
    login_password = params[:user][:password]
    login_uid = params[:user][:nccu_ldap_uid]
    result = false
    ldap = Net::LDAP.new
    #ldap.port = '8001'
    #ldap.host = '127.0.0.1'
     ldap.port = '389' 
     ldap.host = '140.119.166.23' 
    ldap_filter = "(uid=#{login_uid})"
    ldap_base = 'ou=People,dc=nccu,dc=edu,dc=tw'
    ldap.authenticate("cn=uccn,ou=profile,dc=nccu,dc=edu,dc=tw","nccu2ucc") 
    if ldap.bind && login_password!='' #need to block password empty
        result = ldap.bind_as(:base => ldap_base,:filter => ldap_filter,:password=> login_password)
        if result 
          nccu_id = get_nccu_id_from_mid_site(login_uid)
          resource =  nccu_id.nil? ? nil : (User.first(conditions:{ nccu_id: nccu_id }))
           # resource = env['warden'].authenticate!(:check_nccu_ldap)
           # resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
           set_flash_message(:notice, :signed_in) if is_navigational_format?
           if (resource.nil? || nccu_id.nil?)
             flash[:notice] = t('devise.failure.ldap_pass_but_account_not_in_orbit')
             render :action => "new"
           else
             resource_name = resource._type.downcase
             sign_in(resource_name, resource)
             respond_with resource, :location => redirect_location(resource_name, resource)
           end
        else
          flash[:notice] = t('devise.failure.ldap_invalid')
          render :action => "new" 
        end
      else
        flash[:notice] = t('devise.failure.ldap_connection_failed')
        render :action => "new"
      end
    end
private  
  def get_nccu_id_from_mid_site(ldap_id)
    nccu_id = MID_CLIENT.query("SELECT nccu_id FROM rss_aaldap_view WHERE ldap_id='#{ldap_id}' LIMIT 1").first['nccu_id'] rescue nil
        # 
        # if  nccu_id.nil?
        #   #show_error 
        #   p 'account not exist'
        #   #should return?
        # end
        # # User.first(conditions: {  })
        # rss_pautlst_ut = MID_CLIENT.query("SELECT * FROM rss_pautlst_ut WHERE nccu_id='#{nccu_id}' LIMIT 1").first rescue nil
        # # rss_paunit = client.query("SELECT * FROM rss_paunit  LIMIT 1").first rescue nil
        # user = User.find_or_create_by(:nccu_id => nccu_id)
        #  p user
        #  # p rss_paunit
        # 
  end
end
