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 System.Xml;
using System.IO;
using System.Net;
using System.Security;
using System.Collections;
using System.Drawing.Imaging;




using SampleSQLite;



using System.Text.RegularExpressions;

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

using System.Globalization;



namespace Word2010AddIn
{
    public partial class form2 : Form
    {
        int msgLastID;
        List<string> dinosaurs = new List<string>();
        List<string> dinosaurs2 = new List<string>();
        int totalFiles = 0;
        int totalFiles2 = 0;




        DAL dalobj = new DAL();
        DAL2 dalobj2 = new DAL2();


        string contactNID;
        string categoryN;

        string subPath = @"C:\__erpTools\uploadCache";
        
        public form2()
        {
            InitializeComponent();
            InitializeOpenFileDialog();
            bool directoryExists = Directory.Exists(subPath);
            if (directoryExists)
            {
                Directory.Delete(subPath, true);
            }
        }

       



        private void InitializeOpenFileDialog()
        {
            // Set the file dialog to filter for graphics files. 
            this.openFileDialog1.Filter =
                "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" +
                "All files (*.*)|*.*";

            this.openFileDialog1.Multiselect = true;
            this.openFileDialog1.Title = "My Image Browser";
        }
        private void SelectFileButton_Click(object sender, EventArgs e)
        {

        }




        public void moz(String inFTPServerAndPath, String inFullPathToLocalFile, String inUsername, String inPassword,bool hasAttach=false)
        {
            //textBox1.Text = "dddd";
            String filename = Path.GetFileName(inFullPathToLocalFile);

            // Open a request using the full URI, c/file.ext
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(inFTPServerAndPath + "/erp/storage/1391/" + filename);

            // Configure the connection request
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(inUsername, inPassword);
            request.UsePassive = true;
            request.UseBinary = true;
            request.KeepAlive = false;

            // Create a stream from the file
            FileStream stream = File.OpenRead(inFullPathToLocalFile);
            byte[] buffer = new byte[stream.Length];

            // Read the file into the a local stream
            stream.Read(buffer, 0, buffer.Length);

            // Close the local stream
            stream.Close();

            // Create a stream to the FTP server
            Stream reqStream = request.GetRequestStream();
            //MessageBox.Show(reqStream.ToString());

            double percent = 0;
            int offset = 0;
            int chunk = (buffer.Length > 2048) ? 2048 : buffer.Length;
            progressBar1.Value = 0;
           
            while (offset < buffer.Length)
            {
                reqStream.Write(buffer, offset, chunk);
                offset += chunk;
                chunk = (buffer.Length - offset < chunk) ? (buffer.Length - offset) : chunk;
                percent = ((double)offset / (double)buffer.Length) * 100;
                progressBar1.Value = (int)percent;
                
               
            }
            if (hasAttach)
            {
                progressBar2.Value += (int)(100 / totalFiles2);
            }
            else
            {
                progressBar2.Value += (int)(100 / totalFiles);
            }
            
            reqStream.Close();
        }














        public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
        {
            var ratioX = (double)maxWidth / image.Width;
            var ratioY = (double)maxHeight / image.Height;
            var ratio = Math.Min(ratioX, ratioY);

            var newWidth = (int)(image.Width * ratio);
            var newHeight = (int)(image.Height * ratio);

            var newImage = new Bitmap(newWidth, newHeight);
            Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
            return newImage;
        }


        public string PostRequest(string ClientData, string PostURL)
        {

            string responseFromServer = string.Empty;

            try
            {

                // Create a request using a URL that can receive a post. 
                WebRequest request = WebRequest.Create(PostURL);
                // Set the Method property of the request to POST.
                request.Method = "POST";
                // Create POST data and convert it to a byte array.


                byte[] byteArray = Encoding.UTF8.GetBytes(ClientData);
                // Set the ContentType property of the WebRequest.
                request.ContentType = "application/x-www-form-urlencoded";
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
                // Get the response.
                WebResponse response = request.GetResponse();



                if (((HttpWebResponse)response).StatusDescription == "OK")
                {
                    // Get the stream containing content returned by the server.
                    dataStream = response.GetResponseStream();
                    // Open the stream using a StreamReader for easy access.
                    StreamReader reader = new StreamReader(dataStream);
                    // Read the content.
                    responseFromServer = reader.ReadToEnd();
                    MessageBox.Show(responseFromServer.ToString());
                    // Clean up the streams.
                    reader.Close();
                    dataStream.Close();

                }


                response.Close();



                return responseFromServer;
            }
            catch (Exception)
            {
                return responseFromServer;
            }

        }




      private void VaryQualityLevel(string imgAddress,int countID,bool attachedItems=false)
{
   
   
    ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
    System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;

    EncoderParameters myEncoderParameters = new EncoderParameters(1);
    EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 60L);
    myEncoderParameters.Param[0] = myEncoderParameter;

    var image = Image.FromFile(imgAddress);
    var newImage = ScaleImage(image, 900, 1238);


    string value = msgNum1.Text;
    string[] lines = Regex.Split(value, "-");


    if (attachedItems)
    {
        newImage.Save(@"c:\__erpTools\uploadCache\" + lines[1] + "(" + countID + "EX).jpg", jgpEncoder, myEncoderParameters);
        dinosaurs2.Add("c:\\__erpTools\\uploadCache\\" + lines[1] + "(" + countID + "EX).jpg");
    }
    else
    {
        newImage.Save(@"c:\__erpTools\uploadCache\" + lines[1] + "(" + countID + ").jpg", jgpEncoder, myEncoderParameters);
        dinosaurs.Add("c:\\__erpTools\\uploadCache\\" + lines[1] + "(" + countID + ").jpg");
    }

}



private ImageCodecInfo GetEncoder(ImageFormat format)
{

    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

    foreach (ImageCodecInfo codec in codecs)
    {
        if (codec.FormatID == format.Guid)
        {
            return codec;
        }
    }
    return null;
}





private void lastID()
{
    XmlReader xmlReader = XmlReader.Create("http://erp.payabtarh.com/__dbex/lastIDImp.php");
    while (xmlReader.Read())
    {
        if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "lastID"))
        {
            if (xmlReader.HasAttributes)
            {
                msgLastID = Convert.ToInt32(xmlReader.GetAttribute("id"));
                msgNum1.Text = "100/91-" + msgLastID;
            }
        }
    }
}







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 Form2_Load(object sender, EventArgs e)
        
        {

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

            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);
            


        }



        private void doDialogBox(bool attachmentHas = false)
        {


            DialogResult dr = this.openFileDialog1.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                var i = 0;
                Directory.CreateDirectory(subPath);
                if (attachmentHas)
                {
                    totalFiles2 = openFileDialog1.FileNames.Length;
                }
                else
                {
                    totalFiles = openFileDialog1.FileNames.Length;
                }
                attachedList.Items.Clear();
                foreach (String file in openFileDialog1.FileNames)
                {
                    // Create a PictureBox. 
                    try
                    {
                       

                  
                        //flowLayoutPanel1.Controls.Add(pb);

                        if (attachmentHas)
                        {
                            VaryQualityLevel(file.ToString(), i, true);
                        }
                        else
                        {
                            VaryQualityLevel(file.ToString(), i);
                        }

                        attachedList.Items.Add(file.ToString());



                    }
                    catch (SecurityException ex)
                    {
                        // The user lacks appropriate permissions to read files, discover paths, etc.
                        MessageBox.Show("Security error. Please contact your administrator for details.\n\n" +
                            "Error message: " + ex.Message + "\n\n" +
                            "Details (send to Support):\n\n" + ex.StackTrace
                        );
                    }
                    catch (Exception ex)
                    {
                        // Could not load the image - probably related to Windows file system permissions.
                        //  MessageBox.Show("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
                        //     + ". You may not have permission to read the file, or " +
                        //     "it may be corrupt.\n\nReported error: " + ex.Message);
                    }

                    i++;


                }




            }
        }

        private void openFiles_Click(object sender, EventArgs e)
        {
            dinosaurs = new List<string>();
            doDialogBox();      
        }

        private void attachmentFiles_Click(object sender, EventArgs e)
        {
            dinosaurs2 = new List<string>();
            doDialogBox(true);
        }


       
        

        private void uploadBtn_Click(object sender, EventArgs e)
        {
            progressBar2.Value = 0;

            string projectID = "";
            string att1 = "";
            string att2 = "";
            for (int x = 0; x < pList.Items.Count; x++)
            {
                projectID += pList.Items[x].SubItems[1].Text + "/";
            }
            //c:\__erpTools\uploadCache\48651(0).jpg


            foreach (string dinosaur in dinosaurs)
            {
               
                string ftplocation = "ftp://ftp.payabtarh.com";
                string user = "payabtar";
                string password = "kiarash#33";
                moz(ftplocation, dinosaur, user, password);

                att1 += dinosaur.Replace("c:\\__erpTools\\uploadCache\\", "1391/");
                att1 += ",";
                
            }
            att1 = att1.Remove(att1.Length - 1);
            

            progressBar2.Value = 0;
            foreach (string dinosaur in dinosaurs2)
            {
                
                string ftplocation = "ftp://ftp.payabtarh.com";
                string user = "payabtar";
                string password = "kiarash#33";
                moz(ftplocation, dinosaur, user, password,true);
                att2 += dinosaur.Replace("c:\\__erpTools\\uploadCache\\", "1391/");
                att2 += ",";

            }
            if (att2.Length > 0)
            {
                att2 = att2.Remove(att2.Length - 1);
            }

           // MessageBox.Show(att1 + att2);

            string value = msgNum1.Text;

            string[] lines = Regex.Split(value, "-");


            string d1 = "subject=" + subject.Text + "&msgNum=" + lines[1] + "&D1=" + lDate.Text + "&msgNum2=" + msgN2.Text + "&D2=" + lDate2.Text + "&contactID=" + contactNID + "&ProjectL=" + projectID + "&catN=" + categoryN + "&att1=" + att1 + "&att2=" + att2 + "&other=" + other.Text + "&authorID=2&desc=" + desc.Text; ;

           // MessageBox.Show(d1);
           PostRequest(d1, "http://erp.payabtarh.com/post.php");





           
        }

        private void lineShape1_Click(object sender, EventArgs e)
        {

        }

        private void pList_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

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

        private void contactsList_DropDown(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 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 addProject_Click(object sender, EventArgs e)
        {
            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 removeProject_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 label3_Click(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void progressBar1_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void progressBar2_Click(object sender, EventArgs e)
        {

        }

        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 = lDate2.Text = strDate;
            
        }

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

        private void textBox4_TextChanged(object sender, EventArgs e)
        {

        }

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

        private void label13_Click(object sender, EventArgs e)
        {

        }

        private void splitter1_SplitterMoved(object sender, SplitterEventArgs e)
        {

        }

    }
}
