using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NetOffice;
using Outlook = NetOffice.OutlookApi;
using NetOffice.OutlookApi.Enums;
using NetOffice.OutlookApi;
using FCOMMON;

namespace FCM0000.Mail
{
    public partial class fMailBackup : fBase
    {
        public fMailBackup()
        {
            InitializeComponent();
            Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;

            dateTimePicker1.Value = DateTime.Now.AddYears(-2);
            dateTimePicker2.Value = DateTime.Now.AddYears(-1);
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            EnsureVisibleAndUsableSize();
        }
      
        int cntp = 0;
      //  int cnte = 0;
        int cntb = 0;
        List<string> okfolder;
        List<string> nofolder;
        private void button1_Click(object sender, EventArgs e)
        {
            this.okfolder = new List<string>();
            this.nofolder = new List<string>();

            textBox1.Text = textBox1.Text.Trim();
            textBox2.Text = textBox2.Text.Trim();

            var buf1 = textBox1.Text.Split(',');
            var buf2 = textBox2.Text.Split(',');
            foreach(var item in buf1)
            {
                if (string.IsNullOrEmpty(item)) continue;
                if(okfolder.IndexOf(item.ToLower()) == -1) okfolder.Add(item.ToLower());
            }
            foreach (var item in buf2)
            {
                if (string.IsNullOrEmpty(item)) continue;
                if (nofolder.IndexOf(item.ToLower()) == -1) nofolder.Add(item.ToLower());
            }

            if (FCOMMON.Util.MsgQ("진짜?") != DialogResult.Yes) return;
        //    int cnt = 0;
            var fd = new FolderBrowserDialog();
            fd.SelectedPath = this.textBox3.Text;
            if (fd.ShowDialog() != DialogResult.OK) return;

            var path = fd.SelectedPath;

            cntp = 0;
            cntb = 0;
           // cnte = 0;

            Outlook.Application oApp = new Outlook.Application();
            var oNS = oApp.GetNamespace("mapi");
            foreach (MAPIFolder folder in oNS.Folders)
            {
                if (folder.DefaultItemType != OlItemType.olMailItem) continue;
                folderbak(path, folder);
            }
            this.button1.Text = "저장된 메일 " + cntb.ToString() + "건/" + cntp.ToString() + "건 처리";
            this.button1.Refresh();
            FCOMMON.Util.MsgI("백업 성공");


            //get first message


            //var newmail = ol.CreateItem(OlItemType.olMailItem) as Outlook.MailItem;
            //newmail.Display();
            //ol.

            //foreach (var to in tolist)
            //{
            //    if (to.isEmpty()) continue;
            //    var newMail = ol.CreateItem(OlItemType.olMailItem) as Outlook.MailItem;
            //    newMail.Display();
            //    newMail.Subject = this.tbSubject.Text.Trim(); // dr.title;
            //    newMail.To = to;
            //    newMail.CC = tbCC.Text.Trim();
            //    newMail.BCC = tbBCC.Text.Trim();
            //    // newMail.BodyFormat = OlBodyFormat.olFormatHTML;
            //    newMail.HTMLBody = this.tbBody.Html
            //         .Replace("{USER}", FCOMMON.info.Login.nameK)
            //         .Replace("{EUSER}", FCOMMON.info.Login.nameE)
            //         .Replace("{EMAIL}", FCOMMON.info.Login.email)
            //         .Replace("%7BEMAIL%7D", FCOMMON.info.Login.email)
            //         .Replace("{HP}", FCOMMON.info.Login.hp)
            //         .Replace("{TEL}", FCOMMON.info.Login.tel)
            //         .Replace("{ITEM}", tbSubject.Text) + newMail.HTMLBody;



            //}
        }

        void folderbak(string basepatth, MAPIFolder folder)
        {
            if (folder.Folders.Count > 0)
            {
                foreach (var fold in folder.Folders)
                {
                    folderbak(basepatth, fold);
                }
            }
            else
            {
                //폴더명이 지정되었다면 그곳에 포함되어있는지 체크한다.
                if(okfolder.Count > 0)
                {
                    if (okfolder.Contains(folder.Name.ToLower()) == false)
                    {
                        return;
                    }

                }
                if(nofolder.Count > 0)
                {
                    if (nofolder.Contains(folder.Name.ToLower()) == true)
                    {
                        return;
                    }
                }
                var oItems = folder.Items;
                var path = basepatth;// + "\\" + folder.FolderPath.Replace(@"\\", "");
                foreach (object miitem in oItems)
                {
                    var mi = miitem as MailItem;
                    if (mi == null) continue;

                    cntp += 1;

                    if (cntp % 10 == 0)
                    {
                        this.button1.Text = "저장된 메일 " + cntb.ToString() + "건/" + cntp.ToString() + "건 처리";
                        this.button1.Refresh();
                    }

                    if (mi.Subject.StartsWith("회수:")) continue;
                    //var mailitem = oItems.GetFirst() as Outlook.MailItem;

                    //var nowitem = ol.ActiveInspector();
                    //var mailitem = nowitem.CurrentItem as Outlook.MailItem;

                    var sd = DateTime.Parse(dateTimePicker1.Value.ToString("yyyy-MM-dd 00:00:00"));
                    var ed = DateTime.Parse(dateTimePicker2.Value.ToString("yyyy-MM-dd 23:59:59"));

                    //기간을 벗어나면 처리하지 않음
                    if (mi.CreationTime < sd || mi.CreationTime > ed) continue;


                    var subject = mi.Subject.Replace("\t", "").Replace("\r", "").Replace("\n", "").Replace("!", "").Replace("*", "").Replace("\"", "").Replace("@", "").Replace("#", "").Replace("^", "").Replace("&", "").Replace(">", "").Replace("<", "").Replace("/", "").Replace(":", "").Replace(" ", "").Replace("\\", "").Replace("?", "").Replace("%", "").Replace("_", "").Replace(".", "");
                    var filename = textBox4.Text.Trim();
                    filename = filename.Replace("{yyyy}", mi.CreationTime.Year.ToString("0000"));
                    filename = filename.Replace("{mm}", mi.CreationTime.Month.ToString("00"));
                    filename = filename.Replace("{dd}", mi.CreationTime.Day.ToString("00"));
                    filename = filename.Replace("{datetime}", mi.CreationTime.ToString("yyyyMMddHHmmss"));

                    filename = filename.Replace("{sender}", mi.SentOnBehalfOfName);
                    filename = filename.Replace("{subject}", subject);
                    filename = filename.Replace("{messageid}", mi.ConversationID);
                    filename = filename.Replace("{folder}", folder.FolderPath.Replace(@"\\", ""));



                    //filename = string.Format("{0}\\{1}\\{2}_{5}_{6}_{3}.msg",
                    //    mi.CreationTime.Year.ToString("000"),
                    //    mi.CreationTime.Month.ToString("00"),
                    //    mi.CreationTime.Day.ToString("00"),
                    //    mi.CreationTime.ToString("yyyyMMddHHmmss"),
                    //    mi.ConversationID,
                    //    mi.SentOnBehalfOfName,
                    //    mi.Subject.Replace("\t", "").Replace("\r", "").Replace("\n", "").Replace("!", "").Replace("*", "").Replace("\"", "").Replace("@", "").Replace("#", "").Replace("^", "").Replace("&", "").Replace(">", "").Replace("<", "").Replace("/", "").Replace(":", "").Replace(" ", "").Replace("\\", "").Replace("?", "").Replace("%", "").Replace("_", "").Replace(".", ""));

                    var finame = System.IO.Path.Combine(path, filename);
                    var fi = new System.IO.FileInfo(finame);
                    if (fi.Directory.Exists == false) fi.Directory.Create();
                    if ( checkBox1.Checked || fi.Exists == false)
                    {

                        try
                        {
                            cntb += 1;
                            mi.SaveAs(fi.FullName);
                        }
                        catch (System.Exception ex)
                        {
                            Console.WriteLine("mail save err:" + ex.Message);
                        }

                    }
                }
            }

        }
    }
}
