using Microsoft.AspNetCore.Mvc;
using System.DirectoryServices;
using System;

namespace AMESCoreStudio.WebApi.Controllers.BLL
{
    /// <summary>
    /// AD 帳號登入
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class ADUserNameController : Controller
    {
        /// <summary>
        /// AD帳密
        /// </summary>
        /// <param name="ADName">AD伺服器名稱 </param>
        /// <param name="UserName">登入者帳號</param>
        /// <param name="UserPwd">登入者密碼</param>
        /// <returns></returns>
        [HttpGet("GetADUser")]
        [Produces(contentType: "application/json")]

        public string GetADUserNet(string ADName, string UserName, string UserPwd)
        {
            string Msg = "";
            try
            {
                System.DirectoryServices.DirectoryEntry de = new System.DirectoryServices.DirectoryEntry("LDAP://" + ADName, UserName, UserPwd);
                System.DirectoryServices.PropertyCollection pc = de.Properties;
                if (pc == null)
                {
                    Msg += "登入失敗  ";
                }
                else
                {
                    //Msg += "登入成功  ";
                    DirectorySearcher search = new DirectorySearcher(de);
                    search.Filter = "(SAMAccountName=" + UserName + ")";
                    //search.PropertiesToLoad.Add("Name");
                    //search.PropertiesToLoad.Add("displayname");
                    //search.PropertiesToLoad.Add("department");
                    //search.PropertiesToLoad.Add("mail");
                    //search.PropertiesToLoad.Add("title");
                    //search.PropertiesToLoad.Add("cn");
                    SearchResult result = search.FindOne();
                    if (result != null)
                    {
                        Msg += result.Path;
                    }
                }
                return Msg;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}