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.IO;
using System.Drawing.Text;
using System.Threading;

public delegate void XyThreadAdd(string Info);

namespace ImageCatalogCS
{
    public partial class MainForm : Form
    {
        private bool stopAttivo;
        private bool waterSelectColor = false;

        //pool
        private XYThreadPool myPool = new XYThreadPool();

        private int contaImmaginiThread;

        private int maxThreads = 15;
        private int minThreads = 5;

        public MainForm()
        {
            InitializeComponent();
        }

        private void setDefaults()
        {
            txtSorgente.Text = "";
            txtDestinazione.Text = "";
            TextBox3.Text = "tn_";
            TextBox4.Text = "";
            TextBox5.Text = "350";
            TextBox6.Text = "350";
            TextBox27.Text = "2240";
            TextBox28.Text = "2240";
            TextBox9.Text = "0";
            TextBox11.Text = "20";
            TextBox12.Text = "8";
            //TextBox13.Text = ""
            TextBox10.Text = "";
            TextBox14.Text = "430";
            TextBox15.Text = "430";
            TextBox16.Text = "290";
            txtFilePerCartella.Text = "99";
            TextBox19.Text = "100";
            txtSuffissoCartelle.Text = "";
            txtCifreContatore.Text = "2";
            TextBox25.Text = "50";
            TextBox26.Text = "";
            TextBox7.Text = Convert.ToString(15);
            TextBox8.Text = Convert.ToString(5);
            TextBox34.Text = "Yellow";
            TextBox30.Text = "20";
            TextBox31.Text = "6";
            TextBox32.Text = "85";
            TextBox33.Text = "30";


            ComboBox1.Items.Add("Alto");
            ComboBox1.Items.Add("Basso");
            ComboBox1.SelectedIndex = 1;

            ComboBox2.Items.Add("Sinistra");
            ComboBox2.Items.Add("Centro");
            ComboBox2.Items.Add("Destra");
            ComboBox2.SelectedIndex = 1;

            // Create a obejct of InstalledFontCollection
            InstalledFontCollection InstalledFonts = new InstalledFontCollection();
            // Gets the array of FontFamily objects associated with this FontCollection.
            FontFamily[] fontfamilies = InstalledFonts.Families;

            //   Populates font combobox with the font name

            foreach (FontFamily fontFamily in fontfamilies)
            {
                ComboBox3.Items.Add(fontFamily.Name);
            }

            ComboBox3.Text = ComboBox3.Items[0].ToString();

            ComboBox4.Items.Add("Sinistra");
            ComboBox4.Items.Add("Centro");
            ComboBox4.Items.Add("Destra");
            ComboBox4.SelectedIndex = 2;

            ComboBox5.Items.Add("Alto");
            ComboBox5.Items.Add("Centro");
            ComboBox5.Items.Add("Basso");
            ComboBox5.SelectedIndex = 2;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Application.EnableVisualStyles();
            setDefaults();
        }

        private void btnCreaCatalogo_Click(object sender, EventArgs e)
        {
            DateTime timestart;
            DateTime timeStop;

            timestart = DateTime.Now;

            txtFileInfo.Text = string.Empty;
            lblFotoTotaliNum.Text = "0";
            Label18.Text = "0";
            Label43.Text = "-s";

            maxThreads = Convert.ToInt32(TextBox7.Text);
            minThreads = Convert.ToInt32(TextBox18.Text);

            //setPicSettings(txtSorgente.Text, txtDestinazione.Text);
            makeSettingsFromForm();
            ProgressBar1.Minimum = 0;
            ProgressBar1.Step = 1;
            ProgressBar1.Value = 0;

            System.Threading.Thread t1 = new System.Threading.Thread(creaCatalogoThread);


        }

        private void creaCatalogoThread()
{
	System.DateTime timeStart = DateTime.Now;
	myPool.StopThreadPool();
	myPool.StartThreadPool(minThreads, maxThreads);
	contaImmaginiThread = 0;

	//creaImmaginiWithThreadMod(txtSorgente.Text, txtDestinazione.Text)
	//creaimmaginiWithThreadDict(txtSorgente.Text, txtDestinazione.Text);
	ThreadPoolWorkItem ThAttivo = null;
	//int i = 0;

            // fine

	
}

        private int getNumerazione()
        {
            int numerazione = 0;
            if (rdbNumProgressiva.Checked)
            {
                numerazione = (int)FileHelper.numerazione.Progressiva;
            }
            else
            {
                numerazione = (int)FileHelper.numerazione.Files;
            }
            return numerazione;
        }

        private void creaimmaginiWithThreadDict(string SourcePath, string DestPath)
{
	Dictionary<FileInfo, DirectoryInfo> dirSourceDest = new Dictionary<FileInfo, DirectoryInfo>();

	if (chkAggiornaSottodirectory.Checked & chkCreaSottocartelle.Checked) {
		FileHelper helper = new FileHelper(Convert.ToInt32(txtFilePerCartella.Text), txtSuffissoCartelle.Text, Convert.ToInt32(txtCifreContatore.Text), getNumerazione());
		//getfilesrecursive
		dirSourceDest = helper.GetFilesRecursive(new DirectoryInfo(SourcePath), new DirectoryInfo(DestPath), "*.jpg");

	} else if (chkAggiornaSottodirectory.Checked & !chkCreaSottocartelle.Checked) {

	}
    //else if ()

	//= getDirsDict(SourcePath, DestPath)

	KeyValuePair<FileInfo, DirectoryInfo> pair = default(KeyValuePair<FileInfo, DirectoryInfo>);

	foreach (KeyValuePair<FileInfo, DirectoryInfo> pair_loopVariable in dirSourceDest) {
		pair = pair_loopVariable;
		//setLabel10Text("File: " + pair.Key.Name);
		string b = (Convert.ToInt32(Label18.Text) + 1).ToString();

		ImageCreator ClsCreaImmagine = new ImageCreator(pair.Key, pair.Value);
		contaImmaginiThread += 1;
		myPool.InsertWorkItem(pair.Key.Name, new XyThreadAdd(ClsCreaImmagine.CreaImmagineThread), new object[1] { pair.Key.Name }, true);

	}

}

        private Dictionary<string, object> makeSettingsFromForm()
        {
            Dictionary<string, object> settingsDict = new Dictionary<string, object>();
            settingsDict.Add("sourceDirRoot", new DirectoryInfo(txtSorgente.Text));
            settingsDict.Add("destDirRoot", new DirectoryInfo(txtDestinazione.Text));

            settingsDict.Add("DirDividiDestinazione", chkCreaSottocartelle.Checked);
            settingsDict.Add("DirDividiNumFile", txtFilePerCartella.Text);
            settingsDict.Add("DirDividiSuffisso", txtSuffissoCartelle.Text);
            settingsDict.Add("DirDividiNumCifre", txtCifreContatore.Text);

            settingsDict.Add("DirDividiTipoNumerazione", rdbNumProgressiva.Checked ? "Progressiva" : "Files");

            //        if (rdbNumProgressiva.Checked)
            //    settingsDict.Add("DirDividiTipoNumerazione", "Progressiva");
            //else
            //    settingsDict.Add("DirDividiTipoNumerazione", "Files");

            // Checkbox
            settingsDict.Add("creaMiniature", CheckBox1.Checked);
            settingsDict.Add("aggiungiTesto", CheckBox2.Checked);
            settingsDict.Add("grassetto", CheckBox3.Checked);
            settingsDict.Add("logoAggiungi", CheckBox5.Checked);
            settingsDict.Add("usaOrarioTestoApplicare", CheckBox8.Checked);
            //settingsDict.Add("usaOrarioMiniatura", CheckBox12.Checked);
            settingsDict.Add("fotoGrandeDimOrigina", CheckBox15.Checked);

            settingsDict.Add("dimStandard", Convert.ToInt32(TextBox11.Text));
            settingsDict.Add("dimStandardMiniatura", Convert.ToInt32(TextBox25.Text));

            
            

            settingsDict.Add("usaRotazioneAutomatica", chkRotazioneAutomatica.Checked);
            settingsDict.Add("usaForzaJpg", chkForzaJpg.Checked);

            settingsDict.Add("testoNome", CheckBox17.Checked);
            settingsDict.Add("nomeData", CheckBox16.Checked);

            settingsDict.Add("testoFirmaStart", TextBox4.Text);
            settingsDict.Add("testoFirmaStartV", TextBox29.Text);

            settingsDict.Add("dataPartenza", DateTimePicker1.Value);
            settingsDict.Add("testoOrario", TextBox18.Text);

            settingsDict.Add("altezzaSmall", Convert.ToInt32(TextBox6.Text));
            settingsDict.Add("larghezzaSmall", Convert.ToInt32(TextBox5.Text));

            
            settingsDict.Add("aggiungiScritteMiniature", RadioButton3.Checked);
            settingsDict.Add("aggTempoGaraMin", RadioButton5.Checked);
            settingsDict.Add("aggNumTempMin", RadioButton7.Checked);

            settingsDict.Add("dimVert", Convert.ToUInt32(TextBox30.Text));
            settingsDict.Add("margVert", Convert.ToInt32(TextBox31.Text));

            settingsDict.Add("suffisso", TextBox3.Text);
            settingsDict.Add("trasparenza", Convert.ToInt32(TextBox9.Text));
            settingsDict.Add("ilFont", ComboBox3.SelectedItem.ToString());
            

            settingsDict.Add("posizione", ComboBox1.SelectedItem.ToString());
            settingsDict.Add("allineamento", ComboBox2.SelectedItem.ToString());
            settingsDict.Add("margine", Convert.ToInt32(TextBox12.Text));

            settingsDict.Add("logoAltezza", Convert.ToInt32(TextBox14.Text));
            settingsDict.Add("logoLarghezza", Convert.ToInt32(TextBox15.Text));

            settingsDict.Add("fontColoreRGB", ColorTranslator.FromHtml(TextBox34.Text));

            
            settingsDict.Add("logoNomeFile", TextBox10.Text);
            settingsDict.Add("logoTrasparenza", TextBox19.Text);
            settingsDict.Add("logoMargine", TextBox16.Text);
            settingsDict.Add("logoPosizioneH", ComboBox4.Text);
            settingsDict.Add("logoPosizioneV", ComboBox5.Text);

            
            settingsDict.Add("altezzaBig", Convert.ToInt32(TextBox27.Text));
            settingsDict.Add("larghezzaBig", Convert.ToInt32(TextBox28.Text));
            settingsDict.Add("dimMin", Convert.ToInt32(TextBox25.Text));

            settingsDict.Add("testoMin", RadioButton6.Checked);

            settingsDict.Add("jpegQuality", Convert.ToInt32(TextBox32.Text));
            settingsDict.Add("jpegQualityMin", Convert.ToInt32(TextBox33.Text));

            return settingsDict;
        }

        private void setPicSettings(string SourcePath, string DestPath)
        {
            DirectoryInfo SourceDir = new DirectoryInfo(SourcePath);
            DirectoryInfo DestDirStart = new DirectoryInfo(DestPath);
            DirectoryInfo DestDir = null;
           
            PicSettings.directorySorgente = txtSorgente.Text;
            PicSettings.directoryDestinazione = txtDestinazione.Text;


            PicSettings.dimStandard = Convert.ToInt32(TextBox11.Text);
            PicSettings.dimStandardMiniatura = Convert.ToInt32(TextBox25.Text);

            //PicSettings.UsaOrarioMiniatura = CheckBox12.Checked;
            PicSettings.UsaOrarioTestoApplicare = CheckBox8.Checked;
            PicSettings.UsaTempoGaraTestoApplicare = CheckBox7.Checked;

            PicSettings.UsaRotazioneAutomatica = chkRotazioneAutomatica.Checked;
            PicSettings.UsaForzaJpg = chkForzaJpg.Checked;

            if (CheckBox17.Checked)
            {
                PicSettings.TestoNome = true;
            }
            else
            {
                PicSettings.TestoNome = false;

            }

            if (CheckBox16.Checked)
            {
                PicSettings.NomeData = true;
            }
            else
            {
                PicSettings.NomeData = false;
            }
            PicSettings.TestoFirmaStart = TextBox4.Text;
            PicSettings.TestoFirmaStartV = TextBox29.Text;

            PicSettings.DataPartenza = DateTimePicker1.Value;
            PicSettings.TestoOrario = TextBox18.Text;

            PicSettings.AltezzaSmall = Convert.ToInt32(TextBox6.Text);
            PicSettings.LarghezzaSmall = Convert.ToInt32(TextBox5.Text);

            PicSettings.CreaMiniature = CheckBox1.Checked;
            PicSettings.AggiungiScritteMiniature = RadioButton3.Checked;
            PicSettings.AggTempoGaraMin = RadioButton5.Checked;
            PicSettings.AggNumTempMin = RadioButton7.Checked;


            PicSettings.dimVert = Convert.ToInt32(TextBox30.Text);
            PicSettings.margVert = Convert.ToInt32(TextBox31.Text);

            //PicSettings.NomeFileChild = childFile.Name
            PicSettings.Suffisso = TextBox3.Text;
            //PicSettings.Codice = TextBox13.Text

            PicSettings.Trasparenza = Convert.ToInt32(TextBox9.Text);
            PicSettings.IlFont = ComboBox3.SelectedItem.ToString();
            PicSettings.Grassetto = CheckBox3.Checked;

            PicSettings.Posizione = ComboBox1.SelectedItem.ToString();
            PicSettings.Allineamento = ComboBox2.SelectedItem.ToString();
            PicSettings.Margine = Convert.ToInt32(TextBox12.Text);

            PicSettings.LogoAltezza = Convert.ToInt32(TextBox14.Text);
            PicSettings.LogoLarghezza = Convert.ToInt32(TextBox15.Text);

            PicSettings.fontColoreRGB = ColorTranslator.FromHtml(TextBox34.Text);

            PicSettings.LogoAggiungi = CheckBox5.Checked;
            PicSettings.LogoNomeFile = TextBox10.Text;
            PicSettings.LogoTrasparenza = TextBox19.Text;
            PicSettings.LogoMargine = TextBox16.Text;
            PicSettings.LogoPosizioneH = ComboBox4.Text;
            PicSettings.LogoPosizioneV = ComboBox5.Text;

            PicSettings.FotoGrandeDimOrigina = CheckBox15.Checked;
            PicSettings.AltezzaBig = Convert.ToInt32(TextBox27.Text);
            PicSettings.LarghezzaBig = Convert.ToInt32(TextBox28.Text);
            PicSettings.DimMin = Convert.ToInt32(TextBox25.Text);

            PicSettings.TestoMin = RadioButton6.Checked;

            PicSettings.jpegQuality = Convert.ToInt64(TextBox32.Text);
            PicSettings.jpegQualityMin = Convert.ToInt64(TextBox33.Text);

            PicSettings.mainForm = this;


        }

        private void makeSettingsFromFile()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Setup (*.xml)|*.xml|All valid files (*.*)|*.*";
            openFileDialog.FilterIndex = 0;
            openFileDialog.RestoreDirectory = true;

            Dictionary<string, object> settingsDict = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);

            if (DialogResult.OK == openFileDialog.ShowDialog())
            {
                XMLSettings xmlSettings = new XMLSettings(openFileDialog.FileName);
                settingsDict = xmlSettings.getParametriDict();


                settingsDict = bindSettings(settingsDict);
                setLogoMiniature();
                this.Text = string.Format("Image Catalog - {0}", openFileDialog.FileName);
                

            }
        }

        private void setLogoMiniature()
        {
            if (File.Exists(TextBox10.Text))
            {

                PictureBox1.Image = Image.FromFile(TextBox10.Text);
                if (PictureBox1.Image.Height >= PictureBox1.Image.Width)
                {
                    PictureBox1.Height = 160;
                    PictureBox1.Width = Convert.ToInt32(160 * PictureBox1.Image.Width / PictureBox1.Image.Height);
                }
                else
                {
                    PictureBox1.Width = 224;
                    PictureBox1.Height = Convert.ToInt32(224 * PictureBox1.Image.Height / PictureBox1.Image.Width);
                }
            }
        }

        private Dictionary<string, object> bindSettings(Dictionary<string, object> dict)
        {

            txtSorgente.Text = dict["dirSorgente"].ToString();
            txtDestinazione.Text = dict["dirDestinazione"].ToString();
            chkAggiornaSottodirectory.Checked = Convert.ToBoolean(dict["DirSottoDirectory"]);
            
            chkCreaSottocartelle.Checked = Convert.ToBoolean(dict["dirDividiDestinazione"]);
            txtFilePerCartella.Text = dict["dirDividiNumFile"].ToString();
            txtSuffissoCartelle.Text = dict["dirDividiSuffisso"].ToString();
            txtCifreContatore.Text = dict["dirDividiNumCifre"].ToString();

            if (dict["dirDividiTipoNumerazione"].ToString().ToUpper() == "PROGRESSIVA")
                rdbNumProgressiva.Checked = true;
            else
                rdbNumFiles.Checked = true;

            CheckBox1.Checked = Convert.ToBoolean(dict["miniatureCrea"]);
            TextBox3.Text = dict["miniatureSuffisso"].ToString();
            TextBox5.Text = dict["miniatureAltezza"].ToString();
            TextBox6.Text = dict["miniatureLarghezza"].ToString();
            RadioButton3.Checked = Convert.ToBoolean(dict["miniatureAddScritta"]);
            RadioButton4.Checked = Convert.ToBoolean(dict["miniatureAddOrario"]);

            TextBox27.Text = dict["fotoAltezza"].ToString();
            TextBox28.Text = dict["fotoLarghezza"].ToString();

            TextBox11.Text = dict["fontDimensione"].ToString();
            TextBox25.Text = dict["fontDimensioneMiniatura"].ToString();
            CheckBox3.Checked = Convert.ToBoolean(dict["fontBold"]);
            ComboBox3.Text = dict["fontNome"].ToString();

            TextBox4.Text = dict["testoTesto"].ToString();
            TextBox9.Text = dict["testoTrasparente"].ToString();
            TextBox12.Text = dict["testoMargine"].ToString();
            ComboBox1.Text = dict["testoPosizione"].ToString();
            ComboBox2.Text = dict["testoAllineamento"].ToString();

            TextBox10.Text = dict["marchioFile"].ToString();
            TextBox14.Text = dict["marchioAltezza"].ToString();
            TextBox15.Text = dict["marchioLarghezza"].ToString();
            TextBox16.Text = dict["marchioMargine"].ToString();
            ComboBox4.Text = dict["marchioAllOrizzontale"].ToString();
            ComboBox5.Text = dict["marchioAllVerticale"].ToString();
            TextBox19.Text = dict["marchioTrasparenza"].ToString();
            CheckBox5.Checked = Convert.ToBoolean(dict["MarchioAggiungi"]);

            CheckBox7.Checked = Convert.ToBoolean(dict["tempoGara"]);
            CheckBox8.Checked = Convert.ToBoolean(dict["orario"]);
            TextBox18.Text = dict["etichettaOrario"].ToString();

            chkForzaJpg.Checked = Convert.ToBoolean(dict["generaleForzaJpg"]);
            chkRotazioneAutomatica.Checked = Convert.ToBoolean(dict["generaleRotazioneAutomatica"]);

            TextBox30.Text = dict["grandezzaVerticale"].ToString();
            TextBox31.Text = dict["margineVerticale"].ToString();
            CheckBox15.Checked = Convert.ToBoolean(dict["dimensioniOriginali"]);
            TextBox29.Text = dict["testoVerticale"].ToString();
            RadioButton6.Checked = Convert.ToBoolean(dict["nomeMiniatura"]);
            CheckBox16.Checked = Convert.ToBoolean(dict["dataFoto"]);
            CheckBox17.Checked = Convert.ToBoolean(dict["numeroFoto"]);


            RadioButton5.Checked = Convert.ToBoolean(dict["tempoSmall"]);
            RadioButton7.Checked = Convert.ToBoolean(dict["numTempoSmall"]);

            TextBox32.Text = dict["compressioneJpeg"].ToString();
            TextBox33.Text = dict["compressioneJpegMiniatura"].ToString();

            TextBox34.Text = dict["coloreTestoRGB"].ToString();



            return dict;
        }




        private void caricaImpostazioniToolStripMenuItem_Click(object sender, EventArgs e)
        {
            makeSettingsFromFile();
        }

        private void btnStopCreazione_Click(object sender, EventArgs e)
        {
            
        }

        private void informazioniToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutForm about = new AboutForm();
            about.Show();
        }

        private void CheckBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (CheckBox2.Checked)
                panelTesto.Enabled = true;
            else
                panelTesto.Enabled = false;
        }

        private void CheckBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (CheckBox1.Checked)
                panelMiniature.Enabled = true;
                else
                panelMiniature.Enabled = false;
        }

      
        


        

        

        

           
        
    }
}
