using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CatalogVbLib;
using MaddoShared;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
using Microsoft.WindowsAPICodePack.Dialogs;

namespace ImageCatalog
{
    public delegate void XyThreadAdd(string Info);

    public partial class MainForm
    {
        public MainForm()
        {
            InitializeComponent();
            _Button3.Name = "Button3";
            _Button2.Name = "Button2";
            _Button8.Name = "Button8";
            _CheckBox18.Name = "CheckBox18";
            _CheckBox4.Name = "CheckBox4";
            _CheckBox12.Name = "CheckBox12";
            _PictureBox1.Name = "PictureBox1";
            _Button4.Name = "Button4";
            _Label27.Name = "Label27";
            _Button7.Name = "Button7";
            _Button5.Name = "Button5";
            //_btnCreaCatalogo.Name = "btnCreaCatalogo";
            _Button6.Name = "Button6";
            _btnCreaCatalogoAsync.Name = "btnCreaCatalogoAsync";

            _results = new ConcurrentBag<string>();
            UiUpdateEvent += OnUiUpdateEvent;

        }
        private event EventHandler<Tuple<string, int>> UiUpdateEvent;

        delegate void SetTextCallback(Label target, string text);

        private void SetText(Label target, string text)
        {

            if (InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { target, text });
            }
            else
            {
                target.Text = text;
            }
        }
        delegate void SetProgressCallback(ProgressBar target, int amount, int maximum);
        private void SetProgress(ProgressBar target, int amount, int maximum)
        {
            if (InvokeRequired)
            {
                SetProgressCallback d = new SetProgressCallback(SetProgress);
                this.Invoke(d, new object[] { target, amount, maximum });
            }
            else
            {
                target.Maximum = maximum;
                target.Value = amount;
            }
        }
        private void OnUiUpdateEvent(object sender, Tuple<string, int> args)
        {
            SetProgress(ProgressBar1, _results.Count, args.Item2);
            SetText(Label18, _results.Count.ToString());
            SetText(Label10, args.Item1);
            SetText(lblFotoTotaliNum, args.Item2.ToString());
        }

        /* TODO ERROR: Skipped DefineDirectiveTrivia */
        private bool StopAttivo;
        private bool WaterSelectColor = false;

        // Private ContaFotoCuori As Integer
        // Private TaskCuori() As PicInfo

        private XYThreadPool MyPool = new XYThreadPool();
        private int ContaImmaginiThread;
        private int maxThreads = 15;
        private int minThreads = 5;

        private ConcurrentBag<string> _results;

        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 = 4.ToString();
            TextBox8.Text = 4.ToString();
            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
            var InstalledFonts = new InstalledFontCollection();
            // Gets the array of FontFamily objects associated with this FontCollection.
            var 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();

            // ComboBox3.Items.Add("Arial")
            // ComboBox3.Items.Add("Arial Black")
            // ComboBox3.Items.Add("Arial Narrow")
            // ComboBox3.Items.Add("Comic Sans MS")
            // ComboBox3.Items.Add("Courier New")
            // ComboBox3.Items.Add("System")
            // ComboBox3.Items.Add("Times New Roman")
            // ComboBox3.Items.Add("Verdana")
            // ComboBox3.Items.Add("Wingdings")
            // ComboBox3.SelectedIndex = 7

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

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool AllocConsole();

        private void Form1_Load(object sender, EventArgs e)
        {
            Application.EnableVisualStyles();
            setDefaults();
            /* TODO ERROR: Skipped IfDirectiveTrivia */
            AllocConsole();
            /* TODO ERROR: Skipped EndIfDirectiveTrivia */
            Console.WriteLine("Programma avviato");
        }

        private void FixPaths()
        {
            if (txtSorgente.Text.EndsWith(@"\") == false)
            {
                txtSorgente.Text += @"\";
            }

            if (txtDestinazione.Text.EndsWith(@"\") == false)
            {
                txtDestinazione.Text += @"\";
            }
        }

        private void lockUI()
        {
            TabControl1.Enabled = false;
            Button5.Enabled = false;
            Button6.Enabled = false;
            btnCreaCatalogoAsync.Enabled = false;
        }

        private void unlockUI()
        {
            TabControl1.Enabled = true;
            Button5.Enabled = true;
            Button6.Enabled = true;
            btnCreaCatalogoAsync.Enabled = true;
        }

        private void btnCreaCatalogo_Click(object sender, EventArgs e)
        {
            lockUI();
            DateTime timeStart;
            var timeStop = default(DateTime);
            timeStart = DateAndTime.TimeOfDay;
            FixPaths();
            Label10.Text = "";
            lblFotoTotaliNum.Text = "0";
            Label18.Text = "0";
            Label43.Text = "-s";
            maxThreads = Conversions.ToInteger(TextBox7.Text);
            minThreads = Conversions.ToInteger(TextBox8.Text);
            if (rdbNuovoMetodo.Checked)
            {
                setPicSettings(txtSorgente.Text, txtDestinazione.Text);
                ProgressBar1.Minimum = 0;
                ProgressBar1.Step = 1;
                ProgressBar1.Value = 0;
                var t1 = new Thread(creaCatalogoThread);
                t1.IsBackground = false;
                t1.Start();
            }
            else if (rdbVecchioMetodo.Checked)
            {
                creaCatalogo(timeStart, timeStop);
                unlockUI();
            }
        }

        private void creaCatalogoThread()
        {
            var timeStart = DateAndTime.TimeOfDay;
            MyPool.StopThreadPool();
            MyPool.StartThreadPool(minThreads, maxThreads);
            ContaImmaginiThread = 0;

            // creaImmaginiWithThreadMod(txtSorgente.Text, txtDestinazione.Text)
            creaimmaginiWithThreadDict(txtSorgente.Text, txtDestinazione.Text);
            ThreadPoolWorkItem ThAttivo = null;
            int i = 0;
            /* TODO ERROR: Skipped DefineDirectiveTrivia */
            /* TODO ERROR: Skipped IfDirectiveTrivia */

            while (i != ContaImmaginiThread)
            {
                Thread.Sleep(100);
                ThAttivo = MyPool.ExtractWorkItem();
                if (ThAttivo is object)
                {
                    i += 1;
                    // stepProgressBar()
                    int threads = MyPool.GetThreadCount();
                    setLabel10Text("File: " + ThAttivo.m_sName + " Threads: " + threads.ToString());

                    // setLabel18Text(ContaImmaginiThread.ToString)
                    // setLabel18Text(i.ToString)


                    // Label10.Text = "File: " & ThAttivo.m_sName
                    // Label18.Text = ContaImmaginiThread.ToString
                }
            }

            MyPool.StopThreadPool();
            var timeStop = DateAndTime.TimeOfDay;
            setLabel10Text("Finito");
            setLabel43Text(CalcTime(timeStart, timeStop, ContaImmaginiThread));
            /* TODO ERROR: Skipped EndIfDirectiveTrivia */
        }

        private void creaCatalogo(DateTime timeStart, DateTime timeStop)
        {
            // asdfg
            MyPool.StopThreadPool();
            MyPool.StartThreadPool(minThreads, maxThreads);
            ContaImmaginiThread = 0;
            CreaImmaginiWithThread(txtSorgente.Text, txtDestinazione.Text);
            ThreadPoolWorkItem ThAttivo = null;
            int i = 0;
            while (i != ContaImmaginiThread)
            {
                Thread.Sleep(100);
                ThAttivo = MyPool.ExtractWorkItem();
                if (ThAttivo is object)
                {
                    i += 1;
                    Label10.Text = "File: " + ThAttivo.m_sName;
                    Label18.Text = ContaImmaginiThread.ToString();
                }
            }

            MyPool.StopThreadPool();
            timeStop = DateAndTime.TimeOfDay;
            CalcTime(timeStart, timeStop, ContaImmaginiThread);
            Label10.Text = "Finito";
            if (CheckBox22.Checked == true)
            {
                Interaction.Shell(@"%windir%\System32\shutdown.exe");
            }
        }

        private string CalcTime(DateTime timeStart, DateTime timeStop, int numFoto)
        {
            long timediffH, timediffS;
            long timediffM;
            timediffM = DateAndTime.DateDiff(DateInterval.Minute, timeStart, timeStop);
            timediffS = DateAndTime.DateDiff(DateInterval.Second, timeStart, timeStop);
            timediffH = DateAndTime.DateDiff(DateInterval.Hour, timeStart, timeStop);
            // dim s As String = "H:" + timediffH.ToString + " M:" + timediffM.ToString + " S:" + timediffS.ToString

            // Label43.Text = "H:" + timediffH.ToString + " M:" + timediffM.ToString + " S:" + timediffS.ToString
            double fotoSec = numFoto / (double)timediffS;
            double fotoMin = numFoto / (double)timediffM;
            double fotoOra = numFoto / (double)timediffH;
            string s = "S: " + timediffS.ToString() + "; F/s: " + fotoSec.ToString("0.000"); // + " F/m: " + fotoMin.ToString("0.00") + " F/h: " + fotoOra.ToString("0.00")
            return s;
        }

        private string SelectFolder(string startingFolder)
        {
            CommonOpenFileDialog dialog = new CommonOpenFileDialog
            {
                InitialDirectory = startingFolder,
                IsFolderPicker = true
            };
            if (dialog.ShowDialog() != CommonFileDialogResult.Ok) return null;
            var directoryScelta = dialog.FileName;
            if (directoryScelta.EndsWith(@"\") == false)
            {
                directoryScelta += @"\";
            }

            return directoryScelta;

        }

        private void Button2_Click(object sender, EventArgs e)
        {
            var dialogResult = SelectFolder(txtSorgente.Text);
            if (!string.IsNullOrWhiteSpace(dialogResult))
            {
                txtSorgente.Text = dialogResult;
            }

            //CommonOpenFileDialog dialog = new CommonOpenFileDialog();
            //dialog.InitialDirectory = txtSorgente.Text;
            //dialog.IsFolderPicker = true;
            //if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
            //{
            //    string directoryScelta = dialog.FileName;
            //    if (directoryScelta.EndsWith(@"\") == false)
            //    {
            //        directoryScelta += @"\";
            //    }

            //    txtSorgente.Text = directoryScelta;
            //}

            //var DirSearch = new FolderBrowserDialog();
            //DirSearch.SelectedPath = txtSorgente.Text;
            //if (DialogResult.OK == DirSearch.ShowDialog())
            //{
            //    string DirectoryScelta = DirSearch.SelectedPath;
            //    if (DirectoryScelta.EndsWith(@"\") == false)
            //    {
            //        DirectoryScelta += @"\";
            //    }

            //    txtSorgente.Text = DirectoryScelta;
            //}
        }

        private void Button3_Click(object sender, EventArgs e)
        {
            var dialogResult = SelectFolder(txtDestinazione.Text);
            if (!string.IsNullOrWhiteSpace(dialogResult))
            {
                txtDestinazione.Text = dialogResult;
            }

            //var DirSearch = new FolderBrowserDialog();
            //DirSearch.SelectedPath = txtDestinazione.Text;
            //if (DialogResult.OK == DirSearch.ShowDialog())
            //{
            //    string DirectoryScelta = DirSearch.SelectedPath;
            //    if (DirectoryScelta.EndsWith(@"\") == false)
            //    {
            //        DirectoryScelta += @"\";
            //    }

            //    txtDestinazione.Text = DirectoryScelta;
            //}

            // Dim openFileDialog As OpenFileDialog = New OpenFileDialog

            // Dim openFileDialog As OpenFileDialog = New OpenFileDialog

            // openFileDialog.InitialDirectory = TextBox1.Text
            // openFileDialog.Filter = "Bitmap files (*.bmp)|*.bmp|Jpeg files (*.jpg)|*.jpg|All valid files (*.*)|*.*"
            // openFileDialog.FilterIndex = 2
            // openFileDialog.RestoreDirectory = True

            // If DialogResult.OK = openFileDialog.ShowDialog() Then
            // Dim IlNome As String = openFileDialog.FileName
            // Dim NomeFine As String = ""
            // Dim i As Integer

            // Dim Elenco As String()
            // Elenco = IlNome.Split(New Char() {"\"c})
            // For i = 0 To Elenco.Length - 1
            // NomeFine &= Elenco(i) & "\"
            // Next

            // TextBox1.Text = NomeFine
            // End If
        }

        private void Button5_Click(object sender, EventArgs e)
        {
            var SaveFileDlg = new SaveFileDialog();

            // SaveFileDlg.InitialDirectory = "c:\"
            SaveFileDlg.Filter = "Setup (*.xml)|*.xml|All valid files (*.*)|*.*";
            SaveFileDlg.FilterIndex = 0;
            SaveFileDlg.RestoreDirectory = true;
            if (DialogResult.OK == SaveFileDlg.ShowDialog())
            {
                string IlNome = SaveFileDlg.FileName;
                Module1.SetupIni.NomeFileSetup = IlNome;
                Module1.SetupIni.AggiornaParametro("DirSorgente", txtSorgente.Text);
                Module1.SetupIni.AggiornaParametro("DirDestinazione", txtDestinazione.Text);
                Module1.SetupIni.AggiornaParametro("DirSottoDirectory", chkAggiornaSottodirectory.Checked);
                Module1.SetupIni.AggiornaParametro("DirDividiDestinazione", chkCreaSottocartelle.Checked);
                Module1.SetupIni.AggiornaParametro("DirDividiNumFile", txtFilePerCartella.Text);
                Module1.SetupIni.AggiornaParametro("DirDividiSuffisso", txtSuffissoCartelle.Text);
                Module1.SetupIni.AggiornaParametro("DirDividiNumCifre", txtCifreContatore.Text);
                if (rdbNumProgressiva.Checked == true)
                {
                    Module1.SetupIni.AggiornaParametro("DirDividiTipoNumerazione", "Progressiva");
                }
                else
                {
                    Module1.SetupIni.AggiornaParametro("DirDividiTipoNumerazione", "Files");
                }

                Module1.SetupIni.AggiornaParametro("MiniatureCrea", CheckBox1.Checked);
                Module1.SetupIni.AggiornaParametro("MiniatureSuffisso", TextBox3.Text);
                Module1.SetupIni.AggiornaParametro("MiniatureAltezza", TextBox5.Text);
                Module1.SetupIni.AggiornaParametro("MiniatureLarghezza", TextBox6.Text);
                Module1.SetupIni.AggiornaParametro("MiniatureAddScritta", RadioButton3.Checked);
                Module1.SetupIni.AggiornaParametro("MiniatureAddOrario", RadioButton4.Checked);
                Module1.SetupIni.AggiornaParametro("FotoAltezza", TextBox27.Text);
                Module1.SetupIni.AggiornaParametro("FotoLarghezza", TextBox28.Text);
                // SetupIni.AggiornaParametro("FotoCodice", TextBox13.Text)
                // SetupIni.AggiornaParametro("FotoDimOriginali", CheckBox2.Checked)

                Module1.SetupIni.AggiornaParametro("FontDimensione", TextBox11.Text);
                Module1.SetupIni.AggiornaParametro("FontDimensioneMiniatura", TextBox25.Text);
                Module1.SetupIni.AggiornaParametro("FontBold", CheckBox3.Checked);
                Module1.SetupIni.AggiornaParametro("FontNome", ComboBox3.Text);
                Module1.SetupIni.AggiornaParametro("TestoTesto", TextBox4.Text);
                Module1.SetupIni.AggiornaParametro("TestoTrasparente", TextBox9.Text);
                Module1.SetupIni.AggiornaParametro("TestoMargine", TextBox12.Text);
                Module1.SetupIni.AggiornaParametro("TestoPosizione", ComboBox1.Text);
                Module1.SetupIni.AggiornaParametro("TestoAllineamento", ComboBox2.Text);
                Module1.SetupIni.AggiornaParametro("MarchioFile", TextBox10.Text);
                Module1.SetupIni.AggiornaParametro("MarchioAltezza", TextBox14.Text);
                Module1.SetupIni.AggiornaParametro("MarchioLarghezza", TextBox15.Text);
                Module1.SetupIni.AggiornaParametro("MarchioMargine", TextBox16.Text);
                Module1.SetupIni.AggiornaParametro("MarchioAllOrizzontale", ComboBox4.Text);
                Module1.SetupIni.AggiornaParametro("MarchioAllVerticale", ComboBox5.Text);
                Module1.SetupIni.AggiornaParametro("MarchioTrasparenza", TextBox19.Text);
                Module1.SetupIni.AggiornaParametro("MarchioAggiungi", CheckBox5.Checked);
                Module1.SetupIni.AggiornaParametro("TempoGara", CheckBox7.Checked);
                Module1.SetupIni.AggiornaParametro("Orario", CheckBox8.Checked);
                Module1.SetupIni.AggiornaParametro("EtichettaOrario", TextBox18.Text);
                Module1.SetupIni.AggiornaParametro("GeneraleForzaJpg", chkForzaJpg.Checked);
                Module1.SetupIni.AggiornaParametro("GeneraleRotazioneAutomatica", chkRotazioneAutomatica.Checked);
                Module1.SetupIni.AggiornaParametro("GrandezzaVerticale", TextBox30.Text);
                Module1.SetupIni.AggiornaParametro("MargineVerticale", TextBox31.Text);
                Module1.SetupIni.AggiornaParametro("DimensioniOriginali", CheckBox15.Checked);
                Module1.SetupIni.AggiornaParametro("TestoVerticale", TextBox29.Text);
                Module1.SetupIni.AggiornaParametro("NomeMiniatura", RadioButton6.Checked);
                Module1.SetupIni.AggiornaParametro("DataFoto", CheckBox16.Checked);
                Module1.SetupIni.AggiornaParametro("NumeroFoto", CheckBox17.Checked);
                Module1.SetupIni.AggiornaParametro("ColoreTestoRGB", TextBox34.Text);
                Module1.SetupIni.AggiornaParametro("TempoSmall", RadioButton5.Checked);
                Module1.SetupIni.AggiornaParametro("NumTempoSmall", RadioButton7.Checked);
                Module1.SetupIni.AggiornaParametro("CompressioneJpeg", TextBox32.Text);
                Module1.SetupIni.AggiornaParametro("CompressioneJpegMiniatura", TextBox33.Text);
                // 2021
                Module1.SetupIni.AggiornaParametro("ChunkSize", TextBox8.Text);
                Module1.SetupIni.AggiornaParametro("ThreadsCount", TextBox7.Text);
                Module1.SetupIni.SalvaParametriSetup();
                Text = "Image Catalog - " + LeggiSoloNomeFile(IlNome);
            }
        }

        private void Button6_Click(object sender, EventArgs e)
        {
            var openFileDialog = new OpenFileDialog();

            // openFileDialog.InitialDirectory = TextBox1.Text
            openFileDialog.Filter = "Setup (*.xml)|*.xml|All valid files (*.*)|*.*";
            openFileDialog.FilterIndex = 0;
            openFileDialog.RestoreDirectory = true;
            if (DialogResult.OK == openFileDialog.ShowDialog())
            {
                string IlNome = openFileDialog.FileName;
                Module1.SetupIni.NomeFileSetup = IlNome;
                Module1.SetupIni.CaricaParametriSetup();
                txtSorgente.Text = Module1.SetupIni.LeggiParametroString("DirSorgente");
                txtDestinazione.Text = Module1.SetupIni.LeggiParametroString("DirDestinazione");
                chkAggiornaSottodirectory.Checked = Module1.SetupIni.LeggiParametroBoolean("DirSottoDirectory");
                chkCreaSottocartelle.Checked = Module1.SetupIni.LeggiParametroBoolean("DirDividiDestinazione");
                txtFilePerCartella.Text = Module1.SetupIni.LeggiParametroString("DirDividiNumFile");
                txtSuffissoCartelle.Text = Module1.SetupIni.LeggiParametroString("DirDividiSuffisso");
                txtCifreContatore.Text = Module1.SetupIni.LeggiParametroString("DirDividiNumCifre");
                string TestoTemp = Module1.SetupIni.LeggiParametroString("DirDividiTipoNumerazione");
                if (TestoTemp.ToUpper() == "PROGRESSIVA")
                {
                    rdbNumProgressiva.Checked = true;
                }
                else
                {
                    rdbNumFiles.Checked = true;
                }

                CheckBox1.Checked = Module1.SetupIni.LeggiParametroBoolean("MiniatureCrea");
                TextBox3.Text = Module1.SetupIni.LeggiParametroString("MiniatureSuffisso");
                TextBox5.Text = Module1.SetupIni.LeggiParametroString("MiniatureAltezza");
                TextBox6.Text = Module1.SetupIni.LeggiParametroString("MiniatureLarghezza");
                RadioButton3.Checked = Module1.SetupIni.LeggiParametroBoolean("MiniatureAddScritta");
                RadioButton4.Checked = Module1.SetupIni.LeggiParametroBoolean("MiniatureAddOrario");
                TextBox27.Text = Module1.SetupIni.LeggiParametroString("FotoAltezza");
                TextBox28.Text = Module1.SetupIni.LeggiParametroString("FotoLarghezza");
                // TextBox13.Text = SetupIni.LeggiParametroString("FotoCodice")
                // CheckBox2.Checked = SetupIni.LeggiParametroBoolean("FotoDimOriginali")

                TextBox11.Text = Module1.SetupIni.LeggiParametroString("FontDimensione");
                TextBox25.Text = Module1.SetupIni.LeggiParametroString("FontDimensioneMiniatura");
                CheckBox3.Checked = Module1.SetupIni.LeggiParametroBoolean("FontBold");
                ComboBox3.Text = Module1.SetupIni.LeggiParametroString("FontNome");
                if (string.IsNullOrEmpty(TextBox25.Text))
                {
                    TextBox25.Text = "0";
                }

                TextBox4.Text = Module1.SetupIni.LeggiParametroString("TestoTesto");
                TextBox9.Text = Module1.SetupIni.LeggiParametroString("TestoTrasparente");
                TextBox12.Text = Module1.SetupIni.LeggiParametroString("TestoMargine");
                ComboBox1.Text = Module1.SetupIni.LeggiParametroString("TestoPosizione");
                ComboBox2.Text = Module1.SetupIni.LeggiParametroString("TestoAllineamento");
                TextBox10.Text = Module1.SetupIni.LeggiParametroString("MarchioFile");
                TextBox14.Text = Module1.SetupIni.LeggiParametroString("MarchioAltezza");
                TextBox15.Text = Module1.SetupIni.LeggiParametroString("MarchioLarghezza");
                TextBox16.Text = Module1.SetupIni.LeggiParametroString("MarchioMargine");
                ComboBox4.Text = Module1.SetupIni.LeggiParametroString("MarchioAllOrizzontale");
                ComboBox5.Text = Module1.SetupIni.LeggiParametroString("MarchioAllVerticale");
                TextBox19.Text = Module1.SetupIni.LeggiParametroString("MarchioTrasparenza");
                CheckBox5.Checked = Module1.SetupIni.LeggiParametroBoolean("MarchioAggiungi");
                CheckBox7.Checked = Module1.SetupIni.LeggiParametroBoolean("TempoGara");
                CheckBox8.Checked = Module1.SetupIni.LeggiParametroBoolean("Orario");
                TextBox18.Text = Module1.SetupIni.LeggiParametroString("EtichettaOrario");
                chkForzaJpg.Checked = Module1.SetupIni.LeggiParametroBoolean("GeneraleForzaJpg");
                chkRotazioneAutomatica.Checked = Module1.SetupIni.LeggiParametroBoolean("GeneraleRotazioneAutomatica");
                TextBox30.Text = Module1.SetupIni.LeggiParametroString("GrandezzaVerticale");
                TextBox31.Text = Module1.SetupIni.LeggiParametroString("MargineVerticale");
                CheckBox15.Checked = Module1.SetupIni.LeggiParametroBoolean("DimensioniOriginali");
                TextBox29.Text = Module1.SetupIni.LeggiParametroString("TestoVerticale");
                RadioButton6.Checked = Module1.SetupIni.LeggiParametroBoolean("NomeMiniatura");
                CheckBox16.Checked = Module1.SetupIni.LeggiParametroBoolean("DataFoto");
                CheckBox17.Checked = Module1.SetupIni.LeggiParametroBoolean("NumeroFoto");
                RadioButton5.Checked = Module1.SetupIni.LeggiParametroBoolean("TempoSmall");
                RadioButton7.Checked = Module1.SetupIni.LeggiParametroBoolean("NumTempoSmall");
                TextBox32.Text = Module1.SetupIni.LeggiParametroString("CompressioneJpeg");
                TextBox33.Text = Module1.SetupIni.LeggiParametroString("CompressioneJpegMiniatura");
                TextBox34.Text = Module1.SetupIni.LeggiParametroString("ColoreTestoRGB");
                if (File.Exists(TextBox10.Text))
                {
                    PictureBox1.Image = Image.FromFile(TextBox10.Text);
                    if (PictureBox1.Image.Height >= PictureBox1.Image.Width)
                    {
                        PictureBox1.Height = 160;
                        PictureBox1.Width = Conversions.ToInteger(160 * PictureBox1.Image.Width / (double)PictureBox1.Image.Height);
                    }
                    else
                    {
                        PictureBox1.Width = 224;
                        PictureBox1.Height = Conversions.ToInteger(224 * PictureBox1.Image.Height / (double)PictureBox1.Image.Width);
                    }
                }

                Text = "Image Catalog - " + LeggiSoloNomeFile(IlNome);

                // 2021
                TextBox8.Text = Module1.SetupIni.LeggiParametroString("ChunkSize");
                TextBox7.Text = Module1.SetupIni.LeggiParametroString("ThreadsCount");
                
            }
        }

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

            // PicSettings.DestDir = DestDir
            // PicSettings.SourceDir = SourceDir
            // PicSettings.DestDirStart = DestDirStart

            PicSettings.DimStandard = Conversions.ToInteger(TextBox11.Text);
            PicSettings.DimStandardMiniatura = Conversions.ToInteger(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 = Conversions.ToInteger(TextBox6.Text);
            PicSettings.LarghezzaSmall = Conversions.ToInteger(TextBox5.Text);
            PicSettings.CreaMiniature = CheckBox1.Checked;
            PicSettings.AggiungiScritteMiniature = RadioButton3.Checked;
            PicSettings.AggTempoGaraMin = RadioButton5.Checked;
            PicSettings.AggNumTempMin = RadioButton7.Checked;
            PicSettings.DimVert = Conversions.ToInteger(TextBox30.Text);
            PicSettings.MargVert = Conversions.ToInteger(TextBox31.Text);

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

            PicSettings.Trasparenza = Conversions.ToInteger(TextBox9.Text);
            PicSettings.IlFont = ComboBox3.SelectedItem.ToString();
            PicSettings.Grassetto = CheckBox3.Checked;
            PicSettings.Posizione = ComboBox1.SelectedItem.ToString();
            PicSettings.Allineamento = ComboBox2.SelectedItem.ToString();
            PicSettings.Margine = Conversions.ToInteger(TextBox12.Text);
            PicSettings.LogoAltezza = Conversions.ToInteger(TextBox14.Text);
            PicSettings.LogoLarghezza = Conversions.ToInteger(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 = Conversions.ToInteger(TextBox27.Text);
            PicSettings.LarghezzaBig = Conversions.ToInteger(TextBox28.Text);
            PicSettings.DimMin = Conversions.ToInteger(TextBox25.Text);
            PicSettings.TestoMin = RadioButton6.Checked;
            PicSettings.jpegQuality = Conversions.ToLong(TextBox32.Text);
            PicSettings.jpegQualityMin = Conversions.ToLong(TextBox33.Text);
            PicSettings.mainForm = this;
        }

        private List<List<FileInfo>> makeFilesList(string SourcePath)
        {
            var SourceDir = new DirectoryInfo(SourcePath);
            DirectoryInfo DestDir = null;
            int NumFileXDir = Conversions.ToInteger(txtFilePerCartella.Text);
            string SuffixDir = txtSuffissoCartelle.Text;
            int NumCifreDir = Conversions.ToInteger(txtCifreContatore.Text);
            bool DividiFile = false;
            StopAttivo = false;
            int FileConta = 0;
            int ContaFileXDir = 0;
            int ContaDirXDir = 0;
            string TestoTemp = "";
            int ContaTemp = 0;
            var picList = new List<FileInfo>();
            var dirList = new List<List<FileInfo>>();


            // controlla directory principale
            // Dim childFile As FileInfo
            // For Each childFile In SourceDir.GetFiles("*.jpg")
            // picList.Add(childFile)
            // Next

            // picList = getFiles(SourceDir, SearchOption.AllDirectories)

            // dirList.Add(picList)

            // controlla sottodirectory
            if (chkAggiornaSottodirectory.Checked == true)
            {
                foreach (var subDir in SourceDir.GetDirectories())
                {
                    var filesList = new List<FileInfo>();
                    filesList = getFiles(subDir);
                    dirList.Add(filesList);
                }
            }

            return dirList;
        }

        private List<FileInfo> getFiles(DirectoryInfo sourceDir)
        {
            var picList = new List<FileInfo>();
            foreach (var childFile in sourceDir.GetFiles("*.jpg"))
                picList.Add(childFile);
            return picList;
        }

        private Dictionary<FileInfo, DirectoryInfo> getDirsDict(string SourcePath, string DestPath)
        {
            var SourceDir = new DirectoryInfo(SourcePath);
            var DestDirStart = new DirectoryInfo(DestPath);
            DirectoryInfo DestDir = null;
            int NumFileXDir = Conversions.ToInteger(txtFilePerCartella.Text);
            string SuffixDir = txtSuffissoCartelle.Text;
            int NumCifreDir = Conversions.ToInteger(txtCifreContatore.Text);
            bool DividiFile = false;
            StopAttivo = false;
            int FileConta = 0;
            int ContaFileXDir = 0;
            int ContaDirXDir = 0;
            // Dim TestoTemp As String = ""
            // Dim ContaTemp As Integer = 0
            var dirSourceDest = new Dictionary<FileInfo, DirectoryInfo>();
            if (SourceDir.Exists)
            {
                if (chkAggiornaSottodirectory.Checked)
                {
                    FileConta = SourceDir.GetFiles("*.jpg", SearchOption.AllDirectories).GetLength(0);
                }
                else
                {
                    FileConta = SourceDir.GetFiles("*.jpg", SearchOption.TopDirectoryOnly).GetLength(0);
                }

                string a = (Conversions.ToInteger(lblFotoTotaliNum.Text) + FileConta).ToString();
                setLabel17Text(a);
                setProgressBarMaximum(Conversions.ToInteger(a));
                if (chkAggiornaSottodirectory.Checked)
                {
                    foreach (DirectoryInfo directory in SourceDir.GetDirectories())
                    {
                        foreach (FileInfo file in directory.GetFiles(".jpg"))
                        {
                        }
                    }
                }

                foreach (FileInfo file in SourceDir.GetFiles("*.jpg", SearchOption.AllDirectories))
                {
                }

                if (NumFileXDir > 0 & chkCreaSottocartelle.Checked == true & FileConta > NumFileXDir)
                {
                    DividiFile = true;
                }
                else
                {
                    DestDir = DestDirStart;
                    if (!DestDir.Exists)
                    {
                        DestDir.Create();
                    }

                    DividiFile = false;
                }

                var filesList = new List<FileInfo>();
                if (chkAggiornaSottodirectory.Checked)
                {
                    filesList.AddRange(SourceDir.GetFiles("*.jpg", SearchOption.AllDirectories));
                    filesList.AddRange(SourceDir.GetFiles("*.png", SearchOption.AllDirectories));
                }
                else
                {
                    filesList.AddRange(SourceDir.GetFiles("*.jpg", SearchOption.TopDirectoryOnly));
                    filesList.AddRange(SourceDir.GetFiles("*.png", SearchOption.TopDirectoryOnly));
                }

                foreach (FileInfo file in filesList)
                {
                    ContaFileXDir += 1;
                    if (DividiFile == true)
                    {
                        if (ContaFileXDir == ContaDirXDir * NumFileXDir + 1)
                        {
                            ContaDirXDir += 1;
                            string TestoTemp;
                            if (rdbNumProgressiva.Checked == true)
                            {
                                TestoTemp = ContaDirXDir.ToString();
                            }
                            else
                            {
                                TestoTemp = (ContaDirXDir * NumFileXDir).ToString();
                            }

                            for (int ContaTemp = 1, loopTo = NumCifreDir - TestoTemp.Length; ContaTemp <= loopTo; ContaTemp++)
                                TestoTemp = "0" + TestoTemp;
                            DestDir = new DirectoryInfo(Path.Combine(DestDirStart.FullName, SuffixDir, TestoTemp));
                            // DestDir = New DirectoryInfo(DestDirStart.FullName & IIf(Not DestDirStart.FullName.EndsWith("\"), "\", String.Empty).ToString & SuffixDir & TestoTemp)
                            dirSourceDest.Add(file, DestDir);
                            if (!DestDir.Exists)
                            {
                                DestDir.Create();
                            }
                        }
                    }
                }
            }

            return dirSourceDest;
        }

        private void setLabel17Text(string text)
        {
            if (lblFotoTotaliNum.InvokeRequired)
            {
                lblFotoTotaliNum.Invoke(new Action<string>(setLabel17Text), text);
            }
            else
            {
                lblFotoTotaliNum.Text = text;
            }
        }

        private void setLabel10Text(string text)
        {
            if (Label10.InvokeRequired)
            {
                Label10.Invoke(new Action<string>(setLabel10Text), text);
            }
            else
            {
                Label10.Text = text;
            }
        }

        public void stepProgressBar()
        {
            if (ProgressBar1.InvokeRequired)
            {
                ProgressBar1.Invoke(new MethodInvoker(ProgressBar1.PerformStep));
            }
            else
            {
                ProgressBar1.PerformStep();
            }

            setLabel18Text(ProgressBar1.Value.ToString());
        }

        private void setProgressBarMaximum(int value)
        {
            if (ProgressBar1.InvokeRequired)
            {
                ProgressBar1.Invoke(new Action<int>(setProgressBarMaximum), (object)value);
            }
            else
            {
                ProgressBar1.Maximum = value;
            }
        }

        private void setProgressBarValue(int value)
        {
            if (ProgressBar1.InvokeRequired)
            {
                ProgressBar1.Invoke(new Action<int>(setProgressBarValue), (object)value);
            }
            else
            {
                ProgressBar1.Value = value;
            }
        }

        private void setLabel18Text(string text)
        {
            if (Label18.InvokeRequired)
            {
                Label18.Invoke(new Action<string>(setLabel18Text), text);
            }
            else
            {
                Label18.Text = text;
            }
        }

        private void setLabel43Text(string text)
        {
            if (Label43.InvokeRequired)
            {
                Label43.Invoke(new Action<string>(setLabel43Text), text);
            }
            else
            {
                Label43.Text = text;
            }
        }

        private void creaImmaginiWithThreadMod(string SourcePath, string DestPath)
        {
            var SourceDir = new DirectoryInfo(SourcePath);
            var DestDirStart = new DirectoryInfo(DestPath);
            DirectoryInfo DestDir = null;
            int NumFileXDir = Conversions.ToInteger(txtFilePerCartella.Text);
            string SuffixDir = txtSuffissoCartelle.Text;
            int NumCifreDir = Conversions.ToInteger(txtCifreContatore.Text);
            bool DividiFile = false;
            StopAttivo = false;
            int FileConta = 0;
            int ContaFileXDir = 0;
            int ContaDirXDir = 0;
            string TestoTemp = "";
            int ContaTemp = 0;
            if (SourceDir.Exists)
            {
                FileConta = SourceDir.GetFiles("*.jpg").GetLength(0);
                // Label17.Text = (CType(Label17.Text, Integer) + FileConta).ToString
                string a = (Conversions.ToInteger(lblFotoTotaliNum.Text) + FileConta).ToString();
                setLabel17Text(a);
                setProgressBarMaximum(Conversions.ToInteger(a));
                if (NumFileXDir > 0 & chkCreaSottocartelle.Checked == true)
                {
                    if (FileConta > NumFileXDir)
                    {
                        DividiFile = true;
                    }
                    else
                    {
                        DestDir = DestDirStart;
                        if (!DestDir.Exists)
                        {
                            DestDir.Create();
                        }

                        DividiFile = false;
                    }
                }
                else
                {
                    DestDir = DestDirStart;
                    if (!DestDir.Exists)
                    {
                        DestDir.Create();
                    }

                    DividiFile = false;
                }

                foreach (var childFile in SourceDir.GetFiles("*.jpg"))
                {
                    if (StopAttivo == true)
                    {
                        break;
                    }

                    setLabel10Text("File: " + childFile.Name);
                    string b = (Conversions.ToInteger(Label18.Text) + 1).ToString();
                    // setLabel18Text(b)
                    // setProgressBarValue(CInt(b))
                    // Label10.Text = "File: " & childFile.Name
                    // Label18.Text = (CType(Label18.Text, Integer) + 1).ToString
                    // Application.DoEvents()

                    ContaFileXDir += 1;
                    if (DividiFile == true)
                    {
                        if (ContaFileXDir == ContaDirXDir * NumFileXDir + 1)
                        {
                            ContaDirXDir += 1;
                            if (rdbNumProgressiva.Checked == true)
                            {
                                TestoTemp = ContaDirXDir.ToString();
                            }
                            else
                            {
                                TestoTemp = (ContaDirXDir * NumFileXDir).ToString();
                            }

                            var loopTo = NumCifreDir - TestoTemp.Length;
                            for (ContaTemp = 1; ContaTemp <= loopTo; ContaTemp++)
                                TestoTemp = "0" + TestoTemp;
                            if (DestDirStart.FullName.EndsWith(@"\"))
                            {
                                DestDir = new DirectoryInfo(DestDirStart.FullName + SuffixDir + TestoTemp);
                            }
                            else
                            {
                                DestDir = new DirectoryInfo(DestDirStart.FullName + @"\" + SuffixDir + TestoTemp);
                            }

                            if (!DestDir.Exists)
                            {
                                DestDir.Create();
                            }
                        }
                    }

                    // Application.DoEvents()



                    var ClsCreaImmagine = new ImageCreatorSharp(childFile.Name, SourceDir, DestDir, DestDirStart);
                    // ClsCreaImmagine.NomeFileChild = childFile.Name
                    // ClsCreaImmagine.DestDir = DestDir
                    // ClsCreaImmagine.SourceDir = SourceDir
                    // ClsCreaImmagine.DestDirStart = DestDirStart

                    ContaImmaginiThread += 1;
                    //MyPool.InsertWorkItem(childFile.Name, new XyThreadAdd((_) => ClsCreaImmagine.CreaImmagineThread()), new object[1] { childFile.Name }, true);
                }
                // copy all the sub-directories by recursively calling this same routine
                if (chkAggiornaSottodirectory.Checked == true)
                {
                    foreach (var subDir in SourceDir.GetDirectories())
                        creaImmaginiWithThreadMod(subDir.FullName, Path.Combine(DestDir.FullName, subDir.Name));
                }
            }
        }

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

            return numerazione;
        }

        private NumerazioneType GetNumerazioneEnum()
        {
            NumerazioneType numerazioneType;
            if (rdbNumProgressiva.Checked)
            {
                numerazioneType = NumerazioneType.Progressiva; // FileHelper.numerazione.Progressiva
            }
            else
            {
                numerazioneType = NumerazioneType.Files;
            } // FileHelper.numerazione.Files

            return numerazioneType;
        }

        private void creaimmaginiWithThreadDict(string SourcePath, string DestPath)
        {
            var dirSourceDest = new Dictionary<FileInfo, DirectoryInfo>();
            if (chkAggiornaSottodirectory.Checked & chkCreaSottocartelle.Checked)
            {
                var helper = new FileHelper(Conversions.ToInteger(txtFilePerCartella.Text), txtSuffissoCartelle.Text, Conversions.ToInteger(txtCifreContatore.Text), getNumerazione());
                // getfilesrecursive
                dirSourceDest = helper.GetFilesRecursive(new DirectoryInfo(SourcePath), new DirectoryInfo(DestPath), "*.jpg");
            }
            else if (chkAggiornaSottodirectory.Checked & !chkCreaSottocartelle.Checked)
            {

                // = getDirsDict(SourcePath, DestPath)

            }

            foreach (var pair in dirSourceDest)
            {
                setLabel10Text("File: " + pair.Key.Name);
                string b = (Conversions.ToInteger(Label18.Text) + 1).ToString();
                var ClsCreaImmagine = new ImageCreatorSharp(pair.Key, pair.Value);
                ContaImmaginiThread += 1;
                //MyPool.InsertWorkItem(pair.Key.Name, new XyThreadAdd((_) => ClsCreaImmagine.CreaImmagineThread()), new object[1] { pair.Key.Name }, true);
            }
        }

        // il posto giusto dove fare modifiche
        private void CreaImmaginiWithThread(string SourcePath, string DestPath)
        {
            var SourceDir = new DirectoryInfo(SourcePath);
            var DestDirStart = new DirectoryInfo(DestPath);
            DirectoryInfo DestDir = null;
            int NumFileXDir = Conversions.ToInteger(txtFilePerCartella.Text);
            string SuffixDir = txtSuffissoCartelle.Text;
            int NumCifreDir = Conversions.ToInteger(txtCifreContatore.Text);
            bool DividiFile = false;
            StopAttivo = false;
            int FileConta = 0;
            int ContaFileXDir = 0;
            int ContaDirXDir = 0;
            string TestoTemp = "";
            int ContaTemp = 0;
            if (SourceDir.Exists)
            {
                FileConta = SourceDir.GetFiles("*.jpg").GetLength(0);
                lblFotoTotaliNum.Text = (Conversions.ToInteger(lblFotoTotaliNum.Text) + FileConta).ToString();
                if (NumFileXDir > 0 & chkCreaSottocartelle.Checked == true)
                {
                    if (FileConta > NumFileXDir)
                    {
                        DividiFile = true;
                    }
                    else
                    {
                        DestDir = DestDirStart;
                        if (!DestDir.Exists)
                        {
                            DestDir.Create();
                        }

                        DividiFile = false;
                    }
                }
                else
                {
                    DestDir = DestDirStart;
                    if (!DestDir.Exists)
                    {
                        DestDir.Create();
                    }

                    DividiFile = false;
                }

                foreach (var childFile in SourceDir.GetFiles("*.jpg"))
                {
                    if (StopAttivo == true)
                    {
                        break;
                    }
                    // Label10.Text = "File: " & childFile.Name
                    // Label18.Text = (CType(Label18.Text, Integer) + 1).ToString
                    // Application.DoEvents()

                    ContaFileXDir += 1;
                    if (DividiFile == true)
                    {
                        if (ContaFileXDir == ContaDirXDir * NumFileXDir + 1)
                        {
                            ContaDirXDir += 1;
                            if (rdbNumProgressiva.Checked == true)
                            {
                                TestoTemp = ContaDirXDir.ToString();
                            }
                            else
                            {
                                TestoTemp = (ContaDirXDir * NumFileXDir).ToString();
                            }

                            var loopTo = NumCifreDir - TestoTemp.Length;
                            for (ContaTemp = 1; ContaTemp <= loopTo; ContaTemp++)
                                TestoTemp = "0" + TestoTemp;
                            if (DestDirStart.FullName.EndsWith(@"\"))
                            {
                                DestDir = new DirectoryInfo(DestDirStart.FullName + SuffixDir + TestoTemp);
                            }
                            else
                            {
                                DestDir = new DirectoryInfo(DestDirStart.FullName + @"\" + SuffixDir + TestoTemp);
                            }

                            if (!DestDir.Exists)
                            {
                                DestDir.Create();
                            }
                        }
                    }

                    Application.DoEvents();
                    var ClsCreaImmagine = new CreaImmagineSeparateThread();
                    ClsCreaImmagine.DirectorySorgente = txtSorgente.Text;
                    ClsCreaImmagine.DirectoryDestinazione = txtDestinazione.Text;
                    ClsCreaImmagine.DestDir = DestDir;
                    ClsCreaImmagine.SourceDir = SourceDir;
                    ClsCreaImmagine.DestDirStart = DestDirStart;
                    ClsCreaImmagine.DimStandard = Conversions.ToInteger(TextBox11.Text);
                    ClsCreaImmagine.DimStandardMiniatura = Conversions.ToInteger(TextBox25.Text);
                    ClsCreaImmagine.UsaOrarioMiniatura = CheckBox12.Checked;
                    ClsCreaImmagine.UsaOrarioTestoApplicare = CheckBox8.Checked;
                    ClsCreaImmagine.UsaTempoGaraTestoApplicare = CheckBox7.Checked;
                    ClsCreaImmagine.UsaRotazioneAutomatica = chkRotazioneAutomatica.Checked;
                    ClsCreaImmagine.UsaForzaJpg = chkForzaJpg.Checked;
                    if (CheckBox17.Checked)
                    {
                        ClsCreaImmagine.TestoNome = true;
                    }
                    else
                    {
                        ClsCreaImmagine.TestoNome = false;
                    }

                    if (CheckBox16.Checked)
                    {
                        ClsCreaImmagine.NomeData = true;
                    }
                    else
                    {
                        ClsCreaImmagine.NomeData = false;
                    }

                    ClsCreaImmagine.TestoFirmaStart = TextBox4.Text;
                    ClsCreaImmagine.TestoFirmaStartV = TextBox29.Text;
                    ClsCreaImmagine.DataPartenza = DateTimePicker1.Value;
                    ClsCreaImmagine.TestoOrario = TextBox18.Text;
                    ClsCreaImmagine.AltezzaSmall = Conversions.ToInteger(TextBox5.Text);
                    ClsCreaImmagine.LarghezzaSmall = Conversions.ToInteger(TextBox5.Text);
                    ClsCreaImmagine.CreaMiniature = CheckBox1.Checked;
                    ClsCreaImmagine.AggiungiScritteMiniature = RadioButton3.Checked;
                    ClsCreaImmagine.AggTempoGaraMin = RadioButton5.Checked;
                    ClsCreaImmagine.AggNumTempMin = RadioButton7.Checked;
                    ClsCreaImmagine.DimVert = Conversions.ToInteger(TextBox30.Text);
                    ClsCreaImmagine.MargVert = Conversions.ToInteger(TextBox31.Text);
                    ClsCreaImmagine.NomeFileChild = childFile.Name;
                    ClsCreaImmagine.Suffisso = TextBox3.Text;
                    // ClsCreaImmagine.Codice = TextBox13.Text

                    ClsCreaImmagine.Trasparenza = Conversions.ToInteger(TextBox9.Text);
                    ClsCreaImmagine.IlFont = ComboBox3.SelectedItem.ToString();
                    ClsCreaImmagine.Grassetto = CheckBox3.Checked;
                    ClsCreaImmagine.Posizione = ComboBox1.SelectedItem.ToString();
                    ClsCreaImmagine.Allineamento = ComboBox2.SelectedItem.ToString();
                    ClsCreaImmagine.Margine = Conversions.ToInteger(TextBox12.Text);
                    ClsCreaImmagine.LogoAltezza = Conversions.ToInteger(TextBox14.Text);
                    ClsCreaImmagine.LogoLarghezza = Conversions.ToInteger(TextBox15.Text);

                    // ClsCreaImmagine.FontColoreR = CType(TextBox22.Text, Integer)
                    // ClsCreaImmagine.FontColoreG = CType(TextBox23.Text, Integer)
                    // ClsCreaImmagine.FontColoreB = CType(TextBox24.Text, Integer)
                    ClsCreaImmagine.fontColoreRGB = ColorTranslator.FromHtml(TextBox34.Text);
                    ClsCreaImmagine.LogoAggiungi = CheckBox5.Checked;
                    ClsCreaImmagine.LogoNomeFile = TextBox10.Text;
                    ClsCreaImmagine.LogoTrasparenza = TextBox19.Text;
                    ClsCreaImmagine.LogoMargine = TextBox16.Text;
                    ClsCreaImmagine.LogoPosizioneH = ComboBox4.Text;
                    ClsCreaImmagine.LogoPosizioneV = ComboBox5.Text;
                    ClsCreaImmagine.FotoGrandeDimOrigina = CheckBox15.Checked;
                    ClsCreaImmagine.AltezzaBig = Conversions.ToInteger(TextBox27.Text);
                    ClsCreaImmagine.LarghezzaBig = Conversions.ToInteger(TextBox28.Text);
                    ClsCreaImmagine.DimMin = Conversions.ToInteger(TextBox25.Text);
                    ClsCreaImmagine.TestoMin = RadioButton6.Checked;
                    ClsCreaImmagine.jpegQuality = Conversions.ToLong(TextBox32.Text);
                    ClsCreaImmagine.jpegQualityMin = Conversions.ToLong(TextBox33.Text);
                    ContaImmaginiThread += 1;
                    MyPool.InsertWorkItem(childFile.Name, new XyThreadAdd(ClsCreaImmagine.CreaImmagineThread), new object[1] { childFile.Name }, true);
                }
                // copy all the sub-directories by recursively calling this same routine
                if (chkAggiornaSottodirectory.Checked == true)
                {
                    foreach (var subDir in SourceDir.GetDirectories())
                        CreaImmaginiWithThread(subDir.FullName, Path.Combine(DestDir.FullName, subDir.Name));
                }
            }
        }

        private void CopyDirectoryFile(string SourcePath, string DestPath, bool OverWrite = false)
        {
            var SourceDir = new DirectoryInfo(SourcePath);
            var DestDir = new DirectoryInfo(DestPath);
            if (SourceDir.Exists)
            {
                if (!DestDir.Exists)
                {
                    DestDir.Create();
                    // copy all the files of the current directory
                }

                foreach (var childFile in SourceDir.GetFiles())
                {
                    if (OverWrite)
                    {
                        childFile.CopyTo(Path.Combine(DestDir.FullName, childFile.Name), true);
                    }
                    // if overwrite = false, copy the file only if it does not exist
                    // this is done to avoid an IOException if a file already exists
                    // this way the other files can be copied anyway...
                    else if (!File.Exists(Path.Combine(DestDir.FullName, childFile.Name)))
                    {
                        childFile.CopyTo(Path.Combine(DestDir.FullName, childFile.Name), false);
                    }
                    // copy all the sub-directories by recursively calling this same routine
                }

                foreach (var subDir in SourceDir.GetDirectories())
                    CopyDirectoryFile(subDir.FullName, Path.Combine(DestDir.FullName, subDir.Name), OverWrite);
            }
        }

        public Size NewthumbSize(int currentwidth, int currentheight, int MaxPixel, string TipoSize)
        {
            // Calculate the Size of the New image  
            // *** Larghezza, Altezza, Auto

            double tempMultiplier;
            if ((TipoSize.ToUpper() ?? "") == ("Larghezza".ToUpper() ?? ""))
            {
                tempMultiplier = MaxPixel / (double)currentwidth;
            }
            else if ((TipoSize.ToUpper() ?? "") == ("Altezza".ToUpper() ?? ""))
            {
                tempMultiplier = MaxPixel / (double)currentheight;
            }
            else if (currentheight > currentwidth) // portrait  
            {
                tempMultiplier = MaxPixel / (double)currentheight;
            }
            else
            {
                tempMultiplier = MaxPixel / (double)currentwidth;
            }

            var NewSize = new Size((int)Math.Round(currentwidth * tempMultiplier), (int)Math.Round(currentheight * tempMultiplier));
            return NewSize;
        }

        private void Button7_Click(object sender, EventArgs e)
        {
            StopAttivo = true;
            //MyPool.StopThreadPool();

            if (_mainToken != null)
            {
                _mainToken.Cancel();
            }

            unlockUI();
        }

        private void Button4_Click(object sender, EventArgs e)
        {
            var openFileDialog = new OpenFileDialog();

            // openFileDialog.InitialDirectory = TextBox1.Text
            openFileDialog.Filter = "Immagini jpg (*.jpg)|*.jpg|Immagini gif (*.gif)|*.gif|Tutti i file (*.*)|*.*";
            if (TextBox10.Text.Length > 0)
            {
                openFileDialog.FileName = TextBox10.Text;
            }

            openFileDialog.FilterIndex = 0;
            openFileDialog.RestoreDirectory = true;
            if (DialogResult.OK == openFileDialog.ShowDialog())
            {
                TextBox10.Text = openFileDialog.FileName;
                PictureBox1.Image = Image.FromFile(TextBox10.Text);
                if (PictureBox1.Image.Height >= PictureBox1.Image.Width)
                {
                    PictureBox1.Height = 160;
                    PictureBox1.Width = Conversions.ToInteger(160 * PictureBox1.Image.Width / (double)PictureBox1.Image.Height);
                }
                else
                {
                    PictureBox1.Width = 224;
                    PictureBox1.Height = Conversions.ToInteger(224 * PictureBox1.Image.Height / (double)PictureBox1.Image.Width);
                }
            }
        }

        private string LeggiSoloNomeFile(string FileName)
        {
            string Testo = FileName;
            string Risposta = "";
            var Nomi = Testo.Split(new char[] { '\\' });
            if (Nomi.Length > 1)
            {
                Risposta = Nomi[Nomi.Length - 1];
            }

            return Risposta;
        }

        private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            // GetColor()
            // GetPixelColor(PictureBox1.PointToScreen(e.Location)).ToArgb.ToString("X8")

        }

        private void PictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                WaterSelectColor = true;
            }
            else
            {
                WaterSelectColor = false;
            }
        }


        // Private Declare Function CreateDC Lib "gdi32.dll" (ByVal strDriver As String, ByVal strDevice As String, ByVal strOutput As String, ByVal pData As IntPtr) As IntPtr
        // Private Declare Function DeleteDC Lib "gdi32.dll" (ByVal hdc As IntPtr) As Boolean
        // Private Declare Function GetPixel Lib "gdi32.dll" (ByVal hdc As IntPtr, ByVal x As Integer, ByVal y As Integer) As Integer
        // Private Declare Function GetCursorPos Lib "user32.dll" (ByRef lpPoint As Point) As Boolean


        // ''' <summary>
        // ''' Get the color relative to mouse position
        // ''' </summary>
        // Private Sub GetColor()
        // Dim hdcScreen As IntPtr = CreateDC("Display", Nothing, Nothing, IntPtr.Zero)
        // Dim pt As Point = New Point
        // GetCursorPos(pt)
        // Dim cr As Integer = GetPixel(hdcScreen, pt.X, pt.Y)
        // DeleteDC(hdcScreen)
        // Dim clr As Color = Color.FromArgb((cr And &HFF), (cr And &HFF00) >> 8, (cr And &HFF0000) >> 16)
        // PictureBox3.BackColor = clr
        // If WaterSelectColor = True Then
        // PictureBox2.BackColor = clr
        // End If
        // WaterSelectColor = False
        // End Sub


        private Color[] GetPixelColor(Point screenLocation)
        {
            // Dim bm As New Bitmap(1, 1, Imaging.PixelFormat.Format24bppRgb)
            // Dim g As Graphics = Graphics.FromImage(bm)
            // g.CopyFromScreen(screenLocation, New Point(0, 0), New Size(1, 1))
            // Dim result As Color = bm.GetPixel(0, 0)
            // g.Dispose()
            // bm.Dispose()
            // Return result
            return null;
        }

        private void Button8_Click(object sender, EventArgs e)
        {
            var MyDialog = new ColorDialog();
            MyDialog.AllowFullOpen = true;
            // If TextBox22.Text.Length > 0 And TextBox23.Text.Length > 0 And TextBox24.Text.Length > 0 Then
            // If CType(TextBox22.Text, Integer) >= 0 And CType(TextBox23.Text, Integer) >= 0 And CType(TextBox24.Text, Integer) >= 0 Then
            // MyDialog.Color = Color.FromArgb(0, CType(TextBox22.Text, Integer), CType(TextBox23.Text, Integer), CType(TextBox24.Text, Integer))
            // End If
            // End If

            if (MyDialog.ShowDialog() == DialogResult.OK)
            {
                // TextBox22.Text = MyDialog.Color.R.ToString
                // TextBox23.Text = MyDialog.Color.G.ToString
                // TextBox24.Text = MyDialog.Color.B.ToString
                TextBox34.Text = ColorTranslator.ToHtml(MyDialog.Color);
                TextBox34.BackColor = MyDialog.Color;
            }
        }

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

        private void CheckBox18_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox4.Checked = false;
            CheckBox12.Checked = false;
        }

        private void CheckBox4_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox18.Checked = false;
        }

        private void CheckBox12_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox18.Checked = false;
        }

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

        private CancellationTokenSource _mainToken;

        private async void Button1_Click(object sender, EventArgs e)
        {
            lockUI();
            // Dim timeStart As Date
            // Dim timeStop As Date

            _mainToken = new CancellationTokenSource();
            var token = _mainToken.Token;


            // timeStart = TimeOfDay
            FixPaths();
            Label10.Text = "Elaborazione in corso...";
            lblFotoTotaliNum.Text = "0";
            Label18.Text = "0";
            Label43.Text = "-s";
            setPicSettings(txtSorgente.Text, txtDestinazione.Text);
            ProgressBar1.Minimum = 0;
            ProgressBar1.Step = 1;
            ProgressBar1.Value = 0;

            // Await CreaCatalogoParallel()
            var imgStf = new ImageCreationStuff();
            var imageCreationOptions = new ImageCreationStuff.Options();
            imageCreationOptions.AggiornaSottodirectory = chkAggiornaSottodirectory.Checked;
            imageCreationOptions.CreaSottocartelle = chkCreaSottocartelle.Checked;
            imageCreationOptions.FilePerCartella = Conversions.ToInteger(txtFilePerCartella.Text);
            imageCreationOptions.SuffissoCartelle = txtSuffissoCartelle.Text;
            imageCreationOptions.CifreContatore = Conversions.ToInteger(txtCifreContatore.Text);
            imageCreationOptions.NumerazioneType = GetNumerazioneEnum();
            imageCreationOptions.SourcePath = txtSorgente.Text;
            imageCreationOptions.DestinationPath = txtDestinazione.Text;
            imageCreationOptions.MaxThreads = Conversions.ToInteger(TextBox7.Text);
            imageCreationOptions.ChunksSize = Conversions.ToInteger(TextBox8.Text);
            imageCreationOptions.LinearExecution = rdbVecchioMetodo.Checked;

           

            try
            {
                _results = new ConcurrentBag<string>();
                _currentAmount = 0;
                _previousAmount = 0;
                timer1.Tick += Timer1OnTick;

                timer1.Interval = 1000 * 60;
                timer1.Enabled = true;

                string time = await imgStf.CreaCatalogoParallel(imageCreationOptions, _results, UiUpdateEvent, token);
                Label43.Text = time;
                timer1.Enabled = false;
            }
            catch (OperationCanceledException operationCanceledException)
            {
                Console.WriteLine("Operazione cancellata");
            }
            finally
            {
                _mainToken.Dispose();
                
                timer1.Tick -= Timer1OnTick;
            }
            Label10.Text = "Finito";
            unlockUI();
        }

        private int _currentAmount = 0;
        private int _previousAmount = 0;
        private void Timer1OnTick(object sender, EventArgs e)
        {
            _previousAmount = _currentAmount;
            _currentAmount = _results.Count;
            int diff = _currentAmount - _previousAmount;
            SetText(Label43, $"{diff} f/m");
        }

        private void UpdateCounter(string text)
        {
            Label10.Invoke(new Action(() => Label10.Text = text));
        }



        private async Task CreaCatalogoParallel()
        {
            var timeStart = DateAndTime.TimeOfDay;
            ContaImmaginiThread = 0;
            setLabel10Text("Elaborazione in corso...");
            var imgStf = new ImageCreationStuff();
            var imageCreationOptions = new ImageCreationStuff.Options();
            imageCreationOptions.AggiornaSottodirectory = chkAggiornaSottodirectory.Checked;
            imageCreationOptions.CreaSottocartelle = chkCreaSottocartelle.Checked;
            imageCreationOptions.FilePerCartella = Conversions.ToInteger(txtFilePerCartella.Text);
            imageCreationOptions.SuffissoCartelle = txtSuffissoCartelle.Text;
            imageCreationOptions.CifreContatore = Conversions.ToInteger(txtCifreContatore.Text);
            imageCreationOptions.NumerazioneType = GetNumerazioneEnum();
            imageCreationOptions.SourcePath = txtSorgente.Text;
            imageCreationOptions.DestinationPath = txtDestinazione.Text;
            await imgStf.CreaImmaginiParallel(imageCreationOptions, _results, UiUpdateEvent);

            // Await CreaImmaginiParallel(txtSorgente.Text, txtDestinazione.Text)

            setLabel10Text("Finito");
            var timeStop = DateAndTime.TimeOfDay;
            setLabel43Text(CalcTime(timeStart, timeStop, ContaImmaginiThread));
        }

        // Private Async Function CreaImmaginiParallel(ByVal SourcePath As String, ByVal DestPath As String) As Task
        // Dim dataToProcess As List(Of FileData) = New List(Of FileData)

        // 'Dim dirSourceDest As Dictionary(Of FileInfo, DirectoryInfo) = New Dictionary(Of FileInfo, DirectoryInfo)
        // If chkAggiornaSottodirectory.Checked And chkCreaSottocartelle.Checked Then

        // Dim helperSharp As New FileHelperSharp()

        // 'Dim helper As New FileHelper(CInt(txtFilePerCartella.Text), txtSuffissoCartelle.Text, CInt(txtCifreContatore.Text), getNumerazione())
        // 'getfilesrecursive

        // Dim fileHelperOptions As FileHelperOptions = New FileHelperOptions()
        // fileHelperOptions.FilesPerFolder = CInt(txtFilePerCartella.Text)
        // fileHelperOptions.Suffix = txtSuffissoCartelle.Text
        // fileHelperOptions.CounterSize = CInt(txtCifreContatore.Text)
        // fileHelperOptions.NumerationType = GetNumerazioneEnum()

        // dataToProcess = helperSharp.GetFilesRecursive(New DirectoryInfo(SourcePath), New DirectoryInfo(DestPath), "*.jpg", fileHelperOptions)

        // 'dataToProcess = helper.GetFilesRecursiveParallel(New DirectoryInfo(SourcePath), New DirectoryInfo(DestPath), "*.jpg")
        // ElseIf chkAggiornaSottodirectory.Checked And Not chkCreaSottocartelle.Checked Then
        // ' TODO manca tutto?!?!?!?
        // End If

        // Dim scheduler As TaskScheduler = New ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, Environment.ProcessorCount * 2).ConcurrentScheduler

        // Dim test As IEnumerable(Of Task) = From d In dataToProcess Select Task.Factory.StartNew(Sub()
        // 'setLabel10Text("File: " & p.File.Name)

        // Dim b As String = (CType(Label18.Text, Integer) + 1).ToString

        // Dim clsCreaImmagine As New ImageCreator(d.File, d.Directory)

        // clsCreaImmagine.CreaImmagineThread(d.File.Name)

        // ContaImmaginiThread += 1
        // UpdateCounter(ContaImmaginiThread & " " & d.File.Name)
        // End Sub, CancellationToken.None, TaskCreationOptions.LongRunning, scheduler) 'TODO Cancellation Token

        // 'ThreadingHelper.StartAndWaitAllThrottled(test, CType(TextBox7.Text, Integer))

        // Await Task.WhenAll(test)

        // '= getDirsDict(SourcePath, DestPath)
        // 'Parallel.ForEach(dataToProcess,
        // '                 Sub(p, state)
        // '                     'setLabel10Text("File: " & p.File.Name)

        // '                     Dim b As String = (CType(Label18.Text, Integer) + 1).ToString

        // '                     Dim clsCreaImmagine As New ImageCreator(p.File, p.Directory)

        // '                     clsCreaImmagine.CreaImmagineThread(p.File.Name)

        // '                     ContaImmaginiThread += 1
        // '                     UpdateCounter(ContaImmaginiThread & " " & p.File.Name)
        // '                     'MyPool.InsertWorkItem(p.File.Name, New XyThreadAdd(AddressOf ClsCreaImmagine.CreaImmagineThread), New Object(0) {p.File.Name}, True)
        // '                     ' TODO: BREAK ON STOP state.stop()

        // '                 End Sub)

        // 'Dim pair As KeyValuePair(Of FileInfo, DirectoryInfo)
        // 'For Each pair In dirSourceDest

        // '    setLabel10Text("File: " & pair.Key.Name)
        // '    Dim b As String = (CType(Label18.Text, Integer) + 1).ToString

        // '    Dim ClsCreaImmagine As New ImageCreator(pair.Key, pair.Value)
        // '    ContaImmaginiThread += 1
        // '    MyPool.InsertWorkItem(pair.Key.Name, New XyThreadAdd(AddressOf ClsCreaImmagine.CreaImmagineThread), New Object(0) {pair.Key.Name}, True)

        // 'Next
        // End Function
    }

    public class PicInfo
    {
        public DirectoryInfo DirSource, DirDest, DirDestStart;
        public string NomeImmagine;

        public PicInfo(DirectoryInfo Dir_Source, DirectoryInfo Dir_Dest, DirectoryInfo Dir_DestStart, string Nome_Immagine)
        {
            DirSource = Dir_Source;
            DirDest = Dir_Dest;
            DirDestStart = Dir_DestStart;
            NomeImmagine = Nome_Immagine;
        }
    }
}