using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.DirectoryServices;
using System.IO;
using CsvHelper;
using System.Globalization;

namespace Project._Common
{

    public partial class fADSUserList : FCOMMON.fBase
    {
        public fADSUserList()
        {
            InitializeComponent();
        }

        private void fADSUserList_Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            this.lbDomain.Text = this.DomainName();
            this.btInsert.Visible = (FCOMMON.info.Login.level > 9);
            this.tbEntry.Text = "LDAP://OU=Office,OU=Users,OU=People,OU=K4,DC=kr,DC=ds,DC=amkor,DC=com";
            this.tbEntry.Enabled = this.btInsert.Visible;
        }
        public string DomainName()
        {
            var objRootDSE = new DirectoryEntry("LDAP://RootDSE");
            return objRootDSE.Properties["defaultNamingContext"][0].ToString();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            this.listView1.Items.Clear();
            this.listView1.Columns.Clear();
            this.listView1.CheckBoxes = true;
            this.listView1.Columns.Add("sn");
            this.listView1.Columns.Add("cn");
            this.listView1.Columns.Add("disp");
            this.listView1.Columns.Add("dept");
            this.listView1.Columns.Add("title");
            this.listView1.Columns.Add("tel");
            this.listView1.Columns.Add("mail");
            this.listView1.Columns.Add("pager");
            this.listView1.Columns.Add("empno");
            this.listView1.Columns.Add("when");
            this.listView1.Visible = false;

            this.listView1.View = View.Details;

            string[] propliest = new string[] { "whenCreated", "telephonenumber", "title", "employeeNumber", "department", "displayName", "mail", "pager", "sn", "cn" };

            Boolean skipuser = false;
            string dept = string.Empty;
            string whencre = string.Empty;
            string empno = string.Empty;
            string disp = string.Empty;
            string cn = string.Empty;
            string sn = string.Empty;
            string mail = string.Empty;
            string title = string.Empty;
            string pager = string.Empty;
            string tel = string.Empty;

            var deParent = new DirectoryEntry(tbEntry.Text);

            string Nodename = "";
            try
            {
                Nodename = deParent.SchemaClassName;
            }
            catch (Exception ex)
            {
                Util.MsgE(ex.Message + "\n" + tbEntry.Text);
                Nodename = string.Empty;
            }
            if (Nodename != "")
            {
                if (deParent.Name.StartsWith("CN"))
                {
                    //특정사용자 조회

                    foreach (string listIter in propliest)
                    {
                        foreach (object Iter in deParent.Properties[listIter.ToString()])
                        {
                            string strvalue = Iter.ToString();
                            switch (listIter.ToString().ToLower())
                            {
                                case "department":
                                    dept = strvalue;
                                    // var search = toolStripTextBox1.Text.Trim();
                                    // if (search != "") if (dept.IndexOf(search) == -1) skipuser = true;
                                    break;
                                case "whencreated": whencre = strvalue; break;
                                case "title": title = strvalue; break;
                                case "telephonenumber": tel = strvalue; break;
                                case "employeenumber": empno = strvalue; break;
                                case "displayname": disp = strvalue; break;
                                case "mail": mail = strvalue; break;
                                case "pager": pager = strvalue; break;
                                case "sn": sn = strvalue; break;
                                case "cn": cn = strvalue; break;
                            }
                            // if (skipuser) break;
                        }
                        // if (skipuser) break;
                    }


                    var lv = this.listView1.Items.Add(sn);
                    lv.Checked = true;
                    lv.SubItems.Add(cn);
                    lv.SubItems.Add(disp);
                    lv.SubItems.Add(dept);
                    lv.SubItems.Add(title);
                    lv.SubItems.Add(tel);
                    lv.SubItems.Add(mail);
                    lv.SubItems.Add(pager);
                    lv.SubItems.Add(empno);
                    lv.SubItems.Add(whencre);


                }
                else
                {
                    foreach (DirectoryEntry deChild in deParent.Children)
                    {
                        skipuser = false;
                        dept = string.Empty;
                        whencre = string.Empty;
                        empno = string.Empty;
                        disp = string.Empty;
                        cn = string.Empty;
                        sn = string.Empty;
                        mail = string.Empty;
                        title = string.Empty;
                        pager = string.Empty;
                        tel = string.Empty;

                        foreach (string listIter in propliest)
                        {
                            foreach (object Iter in deChild.Properties[listIter.ToString()])
                            {
                                string strvalue = Iter.ToString();
                                switch (listIter.ToString().ToLower())
                                {
                                    case "department":
                                        dept = strvalue;
                                        var search = toolStripTextBox1.Text.Trim();
                                        if (search != "") if (dept.IndexOf(search) == -1) skipuser = true;
                                        break;
                                    case "whencreated": whencre = strvalue; break;
                                    case "title": title = strvalue; break;
                                    case "telephonenumber": tel = strvalue; break;
                                    case "employeenumber": empno = strvalue; break;
                                    case "displayname": disp = strvalue; break;
                                    case "mail": mail = strvalue; break;
                                    case "pager": pager = strvalue; break;
                                    case "sn": sn = strvalue; break;
                                    case "cn": cn = strvalue; break;
                                }
                                if (skipuser) break;
                            }
                            if (skipuser) break;
                        }

                        if (sn == "" || pager == "" || sn.ToUpper().StartsWith("k4") || sn.ToUpper().StartsWith("test")) skipuser = true;
                        if (skipuser) continue;
                        var lv = this.listView1.Items.Add(sn);
                        lv.Checked = true;
                        lv.SubItems.Add(cn);
                        lv.SubItems.Add(disp);
                        lv.SubItems.Add(dept);
                        lv.SubItems.Add(title);
                        lv.SubItems.Add(tel);
                        lv.SubItems.Add(mail);
                        lv.SubItems.Add(pager);
                        lv.SubItems.Add(empno);
                        lv.SubItems.Add(whencre);


                        if (listView1.Items.Count > 500) break;
                    }
                }
            }


            FCOMMON.Util.MsgI("exit");
            this.listView1.Visible = true;
        }

        private void btInsert_Click(object sender, EventArgs e)
        {
            System.Text.StringBuilder sb = new StringBuilder();
            var items = this.listView1.CheckedItems;
            sb.AppendLine("현재 목록의 선택된 자료를 입력하시겠습니까?");
            sb.AppendLine("건수 : " + items.Count.ToString());
            var dlg = FCOMMON.Util.MsgQ(sb.ToString());
            if (dlg != System.Windows.Forms.DialogResult.Yes) return;

            this.prb1.Maximum = items.Count;
            this.prb1.Value = 0;
            foreach (ListViewItem item in items)
            {

                string sn = item.SubItems[0].Text;  //이름
                string cn = item.SubItems[1].Text;  //숏네임
                string disp = item.SubItems[2].Text;// 디스플레이네임
                string dept = item.SubItems[3].Text; // lv.SubItems.Add(dept);
                string title = item.SubItems[4].Text;// lv.SubItems.Add(title);
                string tel = item.SubItems[5].Text; // lv.SubItems.Add(tel);
                string mail = item.SubItems[6].Text; // lv.SubItems.Add(mail);
                string pager = item.SubItems[7].Text; // lv.SubItems.Add(pager);
                string empno = item.SubItems[8].Text; // lv.SubItems.Add(empno);
                string whencre = item.SubItems[9].Text; // lv.SubItems.Add(whencre);

                try
                {
                    //이 대상의 id가 잇는지 체크한다.
                    if (taUser.ExistID(pager) > 0)
                    {
                        taUser.UpdateDept(dept, sn, title, pager);
                    }
                    else
                    {
                        taUser.InsertADSInfo(
                        pager, disp, sn, dept,
                        mail, tel, empno, title,
                        whencre,
                        "Auto Gen", FCOMMON.info.Login.no, DateTime.Now);
                    }

                }
                catch (Exception eX)
                {
                    Console.WriteLine(sn + eX.Message);
                }

                this.prb1.Value += 1;
            }

        }

        private void allSelectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in this.listView1.Items)
                item.Checked = true;
        }

        private void deSelectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in this.listView1.Items)
                item.Checked = !item.Checked;
        }

        private void unSelectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in this.listView1.Items)
                item.Checked = false;
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            var sd = new SaveFileDialog();
            sd.Filter = "csv|*.csv";
            if (sd.ShowDialog() != DialogResult.OK) return;
            var records = new List<List<string>>();
            var data = new List<object>();

            //데이터입력            
            foreach (ListViewItem item in this.listView1.Items)
            {


                data.Add(new
                {
                    sn = item.SubItems[0].Text,
                    cn =    item.SubItems[1].Text,
                    disp =  item.SubItems[2].Text,
                    dept =  item.SubItems[3].Text,
                    title = item.SubItems[4].Text,
                    tel =   item.SubItems[5].Text,
                    mail =  item.SubItems[6].Text,
                    pager = item.SubItems[7].Text,
                    empno = item.SubItems[8].Text,
                    when = item.SubItems[9].Text,
                });

                //records.Add(data);
            }
            using (var writer = new StreamWriter(sd.FileName,false, System.Text.Encoding.Default))
            using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                //foreach (var item in records)
                //{
                //    csv.WriteRecord(item);
                //}

                csv.WriteRecords(data);
            }
            FCOMMON.Util.MsgI("저장완료");
        }
    }
}
