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.Globalization;


using System.Xml;
using System.Data.SQLite;
using System.Data.OleDb;

using System.Net;
using System.IO;
using SampleSQLite;

using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;
using Microsoft.Office.Tools.Word;

using System.Text.RegularExpressions;

using System.Diagnostics;




namespace Word2010AddIn
{
    public partial class projectList : Form
    {
        public projectList()
        {
            InitializeComponent();
        }

        int[] numbers = new int[100];
        int numArray = 0;
        DAL dalobj = new DAL();
        DAL2 dalobj2 = new DAL2();
        int ContactID = 0;
        int msgLastID;
        string dataC;

        string contactNID;
        string eghdamIDN;
        string signIDN;
        string categoryN;






        public void DateConverter()
        {


            PersianCalendar PerCal = new PersianCalendar();
            string Year, Day, Month, strDate;
            Year = PerCal.GetYear(DateTime.Now).ToString();
            Month = PerCal.GetMonth(DateTime.Now).ToString();
            Day = PerCal.GetDayOfMonth(DateTime.Now).ToString();
            if (Day.Length == 1)
                Day = PerCal.GetDayOfMonth(DateTime.Now).ToString().Insert(0, "0");

            if (Month.Length == 1)
            {

                Month = PerCal.GetMonth(DateTime.Now).ToString().Insert(0, "0");

            }

            strDate = Year + '/' + Month + '/' + Day;
            lDate.Text = strDate;
        }


        public void Refresh()
        {


            SQLiteCommand cmd5 = dalobj.ListRefresh();
            contactsList.Items.Clear();
            SQLiteDataAdapter objDataAdapter = new SQLiteDataAdapter(cmd5);
            System.Data.DataTable dt = new System.Data.DataTable();
            objDataAdapter.Fill(dt);
            
            foreach (DataRow dr in dt.Rows)
            {

                ComboboxItem item = new ComboboxItem();
                item.Text = dr[0].ToString();
                item.Value = Int32.Parse(dr[1].ToString());

                contactsList.Items.Add(item);

                
            }

            
            SQLiteCommand cmd5_2 = dalobj2.ListRefresh();
            v.Items.Clear();
            SQLiteDataAdapter objDataAdapter_2 = new SQLiteDataAdapter(cmd5_2);
            System.Data.DataTable dt_2 = new System.Data.DataTable();
            objDataAdapter_2.Fill(dt_2);
            
            foreach (DataRow dr in dt_2.Rows)
            {
                ComboboxItem item = new ComboboxItem();
                item.Text = dr[0].ToString();
                item.Value = Int32.Parse(dr[1].ToString());
                v.Items.Add(item);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

  


            Refresh();
            DateConverter();
            lastID();



            ComboboxItem item = new ComboboxItem();
            item.Text = "قرارداد و حق الزحمه";
            item.Value = 1;
           
            category.Items.Add(item);


            ComboboxItem item2 = new ComboboxItem();
            item2.Text = "طراحی";
            item2.Value = 2;
            category.Items.Add(item2);

            ComboboxItem item3 = new ComboboxItem();
            
            item3.Text = "ژئوتکنیک";
            item3.Value = 3;
            category.Items.Add(item3);


            ComboboxItem item4 = new ComboboxItem();
           
            item4.Text = "فاز سه";
            item4.Value = 4;
            category.Items.Add(item4);


            ComboboxItem item5 = new ComboboxItem();
           
            item5.Text = "سایر";
            item5.Value = 5;
            category.Items.Add(item5);
            


            signText.Text = "با تشکر  " + Environment.NewLine + "بهراد جبار پور" + Environment.NewLine + "مدیر عامل";         
            
        }
     


        
        private void lastID()
        {
            XmlReader xmlReader = XmlReader.Create("http://erp.payabtarh.com/__dbex/lastID.php");
            int i = 0;
            while (xmlReader.Read())
            {

                if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "lastID"))
                {
                    if (xmlReader.HasAttributes)
                    {
                       msgLastID = Convert.ToInt32(xmlReader.GetAttribute("id"));
                       messageNum.Text = "100/91-" + msgLastID;
                    }
                }


              

                if ((xmlReader.NodeType == XmlNodeType.Element) && ( xmlReader.Name == "users"))
                {

                    ComboboxItem item = new ComboboxItem();
                    item.Text = xmlReader.GetAttribute("name");
                    item.Value = Int32.Parse(xmlReader.GetAttribute("id").ToString());

                    


                    if (xmlReader.HasAttributes)
                    {
                        eghdamID.Items.Add(item);

                    }
                }
                if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "signers"))
                {

                    ComboboxItem item = new ComboboxItem();
                    item.Text = xmlReader.GetAttribute("name");
                    item.Value = Int32.Parse(xmlReader.GetAttribute("id").ToString());


                    if (xmlReader.HasAttributes)
                    {
                        signerID.Items.Add(item);

                    }

                    
                }
                i++;
            }
        }




public void reNewProjectsDatabase()
        {
            dalobj2.dellAll();
            XmlReader xmlReader = XmlReader.Create("http://erp.payabtarh.com/__dbex/project_xml.php");
            while (xmlReader.Read())
            {
                if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "projects"))
                {
                    if (xmlReader.HasAttributes)
                    {
                        dalobj2.Insert(xmlReader.GetAttribute("id"), xmlReader.GetAttribute("name"));
                    }
                }
            }
            MessageBox.Show("projects database updated");
        }
       public void reNewContactsDatabase()
        {



            dalobj.dellAll();
            XmlReader xmlReader = XmlReader.Create("http://erp.payabtarh.com/__dbex/contact_xml.php");
            while (xmlReader.Read())
            {
                if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "contact"))
                {
                    if (xmlReader.HasAttributes)
                    {
                        dalobj.Insert(xmlReader.GetAttribute("id"), xmlReader.GetAttribute("name"));
                       

                    }
                }
            }
            MessageBox.Show("contacts database updated");
        }


        


       


        private void cb_TextUpdate(object sender, EventArgs e)
        {

            contactsList.DroppedDown = false;
        }


        private void contactsList_DropDown(object sender, EventArgs e)
        {

          
        }


        private void postWORD()
        {

            Globals.ThisAddIn.Application.ActiveDocument.Content.WholeStory();
            Globals.ThisAddIn.Application.ActiveDocument.Content.Copy();

            IDataObject Data1;
            Data1 = Clipboard.GetDataObject();
            string str = Data1.GetData(DataFormats.Rtf).ToString();
            richTextBox1.Rtf = str;

            string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            //MessageBox.Show(path);

            var desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            desktopFolder = Path.Combine(desktopFolder, "___ErpTemp");
            var fullFileName = Path.Combine(desktopFolder, "t.rtf");


            richTextBox1.SaveFile(fullFileName, RichTextBoxStreamType.RichText);

            // MessageBox.Show("Step 1 passed ");

            var wordApp = new Microsoft.Office.Interop.Word.Application();
            var currentDoc = wordApp.Documents.Open(fullFileName);
            fullFileName = Path.Combine(desktopFolder, "t");
            currentDoc.SaveAs(fullFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault);
            currentDoc.Close();
            wordApp.Quit();

            // MessageBox.Show("Step 2 passed ");


            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

            Microsoft.Office.Interop.Word.Document wordDoc = new Microsoft.Office.Interop.Word.Document();
            Object oMissing = System.Reflection.Missing.Value;
            wordDoc = word.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            word.Visible = false;
            fullFileName = Path.Combine(desktopFolder, "t.docx");
            Object filepath = fullFileName;
            Object confirmconversion = System.Reflection.Missing.Value;
            Object readOnly = false;
            fullFileName = Path.Combine(desktopFolder, "t.html");
            Object saveto = fullFileName;
            Object oallowsubstitution = System.Reflection.Missing.Value;

            wordDoc = word.Documents.Open(ref filepath, ref confirmconversion, ref readOnly, ref oMissing,
                                          ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                          ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                          ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            object fileFormat = WdSaveFormat.wdFormatFilteredHTML;
            wordDoc.SaveAs(ref saveto, ref fileFormat, ref oMissing, ref oMissing, ref oMissing,
                           ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                           ref oMissing, ref oMissing, ref oMissing, ref oallowsubstitution, ref oMissing,
                           ref oMissing);

            word.Quit();

            //  MessageBox.Show("Step 3 passed ");


            Process[] prs = Process.GetProcesses();


            foreach (Process pr in prs)
            {
                if (pr.ProcessName == "erp_tools__word_addin")
                {

                    pr.Kill();

                }

            }
            fullFileName = Path.Combine(desktopFolder, "erp_tools__word_addin.exe");
            Process.Start(fullFileName);


        }

        private void button2_Click(object sender, System.EventArgs e)
        {




            string projectID = "";
            for (int x = 0; x < pList.Items.Count; x++)
            {
                projectID += pList.Items[x].SubItems[1].Text + "/";
            }


            string value = messageNum.Text;

            string[] lines = Regex.Split(value, "-");
            //MessageBox.Show(lines[1]);


            var desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            desktopFolder = Path.Combine(desktopFolder, "___ErpTemp");
            var fullFileName = Path.Combine(desktopFolder, "t.txt");
            File.WriteAllBytes(fullFileName, Encoding.UTF8.GetBytes("sub1=" + subject.Text + "&sub2=" +
            subject2.Text + "&sign=" + signText.Text + "&copies=" + copiesText.Text + "&attach=" + attachBox.Checked.ToString()
            + "&date=" + lDate.Text + "&num=" + messageNum.Text + "&contactID=" + contactNID + "&projectID=" + projectID

            + "&eghdamID=" + eghdamIDN
            + "&signID=" + signIDN
            + "&catID=" + categoryN
            + "&ID=" + lines[1]
            + "&other=" + other.Text
            + "&authorID=2"




            ));


            postWORD();


          
           
            

            


        }

        private void button1_Click(object sender, EventArgs e)
        {



            //MessageBox.Show((project_cb.SelectedItem as ComboboxItem).Text.ToString());

          
                ListViewItem lv = new ListViewItem((v.SelectedItem as ComboboxItem).Text.ToString());
                lv.SubItems.Add((v.SelectedItem as ComboboxItem).Value.ToString());

                pList.Items.Add(lv);

               

               
            


              
            
        }


        private void v_DropDown(object sender, EventArgs e)
        {
            SQLiteCommand cmd51 = dalobj2.reNew(v.Text);
            v.Items.Clear();
            SQLiteDataAdapter objDataAdapter = new SQLiteDataAdapter(cmd51);
            System.Data.DataTable dt = new System.Data.DataTable();
            objDataAdapter.Fill(dt);

            foreach (DataRow dr in dt.Rows)
            {

                ComboboxItem item = new ComboboxItem();
                item.Text = dr[0].ToString();
                item.Value = Int32.Parse(dr[1].ToString());

                v.Items.Add(item);

            }

        }



        private void contactsList_DropDown_1(object sender, EventArgs e)
        {

            SQLiteCommand cmd5 = dalobj.reNew(contactsList.Text);
           
            contactsList.Items.Clear();
            SQLiteDataAdapter objDataAdapter = new SQLiteDataAdapter(cmd5);
            System.Data.DataTable dt = new System.Data.DataTable();
            objDataAdapter.Fill(dt);

            foreach (DataRow dr in dt.Rows)
            {

                ComboboxItem item = new ComboboxItem();
                item.Text = dr[0].ToString();
                item.Value = Int32.Parse(dr[1].ToString());

                contactsList.Items.Add(item);

            }
        }

        private void contactsList_TextChanged(object sender, EventArgs e)
        {
            contactsList.DroppedDown = false;
        }

        private void pList_SelectedIndexChanged(object sender, EventArgs e)
        {


            if (pList.SelectedItems.Count > 0)
            {
               // MessageBox.Show(pList.SelectedItems[0].Text);
               // MessageBox.Show(pList.SelectedItems[0].Index.ToString());

               // pList.Items.Remove(pList.SelectedItems[0]);
            }
         
            
        }

        private void label13_Click(object sender, EventArgs e)
        {

        }

        private void label14_Click(object sender, EventArgs e)
        {

        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (pList.SelectedItems.Count > 0)
            {
                pList.Items.Remove(pList.SelectedItems[0]);
               // contactNID =  (pList.SelectedItems[0] as ComboboxItem).Value.ToString();
            }
        }

        private void contactsList_SelectedValueChanged(object sender, EventArgs e)
        {
            //MessageBox.Show((contactsList.SelectedItem as ComboboxItem).Value.ToString());
            contactNID = (contactsList.SelectedItem as ComboboxItem).Value.ToString();
        }

        private void eghdamID_SelectedValueChanged(object sender, EventArgs e)
        {
            eghdamIDN = (eghdamID.SelectedItem as ComboboxItem).Value.ToString();
        }

        private void category_SelectedIndexChanged(object sender, EventArgs e)
        {
            categoryN = (category.SelectedItem as ComboboxItem).Value.ToString();
        }

        private void signerID_SelectedIndexChanged(object sender, EventArgs e)
        {
            signIDN = (signerID.SelectedItem as ComboboxItem).Value.ToString();
        }

        private void label17_Click(object sender, EventArgs e)
        {

        }

        private void label16_Click(object sender, EventArgs e)
        {

        }

        


    }
}
