using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using KlassenBIB;
using System.Diagnostics;
using System.IO;
using SanShared;
using FluentFTP;
using System.Collections;
using Syncfusion.Windows.Forms.Chart;

namespace SanSystem
{
    
    public partial class UCInliner : UserControl
    {
        enum TabPages
        {
            VORRAUSSETZUNGEN = 0,
            LINERGRUNDLAGEN
        }
        InlinerSanierung inliner = null;
        string destinationPath = string.Empty;
        List<string> filenames = new List<string>();
        public UCInliner(InlinerSanierung san)
        {
            InitializeComponent();
            inliner = san;
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (inliner == null) throw new Exception("Inliner is null");
            TabControl tb = (TabControl)sender;
            if (tb == null) return;
            switch (tb.SelectedIndex)
            {
                
                case (int)TabPages.LINERGRUNDLAGEN:
                    txt_walze_distance.DataBindings.Clear();
                    txt_vakuum.DataBindings.Clear();
                    txt_temp_harz.DataBindings.Clear();
                    txt_charge_harz.DataBindings.Clear();
                    txt_charge_liner.DataBindings.Clear();
                    dt_kalibrierdatum.DataBindings.Clear();
                    txt_liner.DataBindings.Clear();
                    txt_harz.DataBindings.Clear();

                    txt_harz.DataBindings.Add(new Binding("Text", inliner, "HarzTyp"));
                    txt_liner.DataBindings.Add(new Binding("Text", inliner, "LinerTyp"));
                    txt_walze_distance.DataBindings.Add(new Binding("Text", inliner, "KalibierWalzenAbstand"));
                    txt_vakuum.DataBindings.Add(new Binding("Text", inliner, "KalibrierUnterdruck"));
                    txt_temp_harz.DataBindings.Add(new Binding("Text", inliner, "HarzKalibrierTemperatur"));
                    txt_charge_harz.DataBindings.Add(new Binding("Text", inliner, "HarzChargenummer"));
                    txt_charge_liner.DataBindings.Add(new Binding("Text", inliner, "LinerChargenummer"));
                    dt_kalibrierdatum.DataBindings.Add(new Binding("Value", inliner, "DatumKalibrierung"));
                    break;
            }
        }

        private void UCInliner_Load(object sender, EventArgs e)
        {
            CheckDirectories();
            cb_genehmigung.DataBindings.Clear();
            cb_stvo.DataBindings.Clear();
            cb_wasserhaltung.DataBindings.Clear();
            txt_temp_aussen.DataBindings.Clear();
            txt_temp_kanal.DataBindings.Clear();
            cbb_wetter.DataBindings.Clear();

            cb_fertig.DataBindings.Add(new Binding("Checked", inliner, "fertig"));
            cbb_wetter.DataBindings.Add(new Binding("Text", inliner, "Wetter"));
            if (inliner.Datum != null)
                dt_eingebaut.DataBindings.Add(new Binding("Value", inliner, "Datum"));
            else
                dt_eingebaut.Enabled = false;
            cb_genehmigung.DataBindings.Add(new Binding("Checked", inliner, "genehmigungVorhanden"));
            cb_stvo.DataBindings.Add(new Binding("Checked", inliner, "sTVOAbsicherung"));
            cb_wasserhaltung.DataBindings.Add(new Binding("Checked", inliner, "wasserhaltungEingerichtet"));
            txt_temp_aussen.DataBindings.Add(new Binding("Text", inliner, "TempAusen"));
            txt_temp_kanal.DataBindings.Add(new Binding("Text", inliner, "TempKanal"));
            
        }

        private void cb_fertig_CheckedChanged(object sender, EventArgs e)
        {
            if(cb_fertig.CheckState == CheckState.Checked)
            {
                if(inliner.Datum == null)
                {
                    inliner.Datum = DateTime.Now;
                    dt_eingebaut.DataBindings.Clear();
                    dt_eingebaut.DataBindings.Add(new Binding("Value", inliner, "Datum"));
                    dt_eingebaut.Enabled = true;

                }
            }
        }

        private void CheckDirectories()
        {
            destinationPath = inliner.CheckVerzeichnisse(Global.Instance.Projektpfad);
        }

        private void btn_get_temp_Click(object sender, EventArgs e)
        {
            ITemperature temperature = TempCAN.TemperaturBuilder.Temperatur(TempCAN.TemperaturSchnittstellen.TINKERFORGE);

            double temperatur = temperature.GetTemperatur();
            inliner.TempAusen = temperatur;
            

            txt_temp_aussen.Update();
        }

        private  void DownloadFromUV()
        {
            Progress<double> progress = new Progress<double>(x =>
            {
                if (x < 0)
                {

                }
                else
                {
                    ftpProgress.Value = Convert.ToInt32(x);
                }
            });
            try
            {

                FtpClient client = new FtpClient("192.168.250.2");
                client.Port = 21;
                client.DataConnectionType = FtpDataConnectionType.AutoActive;
                client.Credentials = new System.Net.NetworkCredential("default", "default");
                client.Connect();
                //client.ListingParser = FtpParser.UnixAlt;

                ListFiles(client, "/at0/");
                FtpClient newClient = null;
                client.Dispose();

                FtpClient newclient = null;
                foreach (string file in filenames)
                {
                    newClient = new FtpClient("192.168.250.2");
                    newClient.Port = 21;
                    newClient.DataConnectionType = FtpDataConnectionType.AutoActive;
                    newClient.Credentials = new System.Net.NetworkCredential("default", "default");

                    if (newClient.IsConnected)
                    {
                        newClient.Connect();
                    }
                    string[] _tdateiname = file.Split('/');
                    string dateiname = _tdateiname[_tdateiname.Length - 1];
                    string ordner = _tdateiname[_tdateiname.Length - 2];

                    newClient.DownloadFile(Path.Combine(destinationPath, ordner, dateiname), file);
                    //client.DeleteFile(file);

                }
            }
            catch (TimeoutException ex)
            {
                MessageBox.Show("Die anlage reagiert nicht!");
            }

        }

        private void btn_transfer_ftp_Click(object sender, EventArgs e)
        {
            filenames.Clear();
            if (MessageBox.Show("Bitte stellen Sie sicher, dass der Server antwortet und dass nur die Dateien vorhanden sind!", "WARNUNG", MessageBoxButtons.OKCancel, MessageBoxIcon.Stop) == DialogResult.OK)
            {
                DownloadFromUV();               
            }
        }

        private void ListFiles(FtpClient client, string directory)
        {
            client.ListingParser = FtpParser.Unix;
            foreach (FtpListItem item in client.GetListing(directory, FtpListOption.ForceNameList))
            {
                if (item.Type == FtpFileSystemObjectType.File)
                {
                    filenames.Add(item.FullName);
                }
                else if (item.Type == FtpFileSystemObjectType.Directory)
                {
                    ListFiles(client, item.FullName);
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Hashtable grunddaten = new Hashtable()
            {
                {"KL_Wetter","Trocken" }
            };
            List<BilderObject> bilderO = new List<BilderObject>();
            bilderO.Add(new BilderObject()
            {
                ImgID = 1,
                Kommentar = "TestBild",
                Path = @"C:\Users\Damian\Desktop\SanVerwaltung\SanSystem\bin\Debug\projekte\18-850\SW01-SW02\Schachtanbindung\4d0a1627-bd51-48d6-a27e-a4c6691b02d2.jpg"
            });
            BerichtGen.Options options = new BerichtGen.Options("", "", "", grunddaten,bilderO);
            options.ShowDialog();
        }


        private static ChartControl getGraph(string csvFile)
        {
            Size size = new Size(600, 400);

            ChartControl chartControl = new ChartControl();
            chartControl.Size = size;

            ChartAxis axis = chartControl.PrimaryYAxis;
            ChartAxis axis0 = new ChartAxis(ChartOrientation.Vertical);
            ChartAxis axis1 = new ChartAxis(ChartOrientation.Vertical);

            ChartAxisLayout layout1 = new ChartAxisLayout();
            ChartAxisLayout layout2 = new ChartAxisLayout();

            chartControl.Axes.Add(axis0);
            chartControl.Axes.Add(axis1);

            layout1.Spacing = 12;
            layout2.Spacing = 12;
            layout1.Axes.Add(axis);
            layout2.Axes.Add(axis0);
            layout2.Axes.Add(axis1);

            chartControl.ChartArea.YLayouts.Add(layout1);
            chartControl.ChartArea.YLayouts.Add(layout2);

            ChartSeries temperaturChart = new ChartSeries("Temperatur", ChartSeriesType.Line);
            ChartSeries druckChart = new ChartSeries("Druck", ChartSeriesType.Line);
            if (!File.Exists(csvFile)) return null;
            string[] input = File.ReadAllLines(csvFile);
            int counter = 0;
            foreach (string pars in input)
            {
                string[] parts = pars.Split(',');
                if (parts[0].Equals("Group1") || parts[1].Equals("(END)")) continue;
                double temperatur = double.Parse(parts[1].Replace('.', ','));
                double druck = double.Parse(parts[2].Replace('.', ','));

                temperaturChart.Points.Add(counter, temperatur);
                druckChart.Points.Add(counter, druck);
                counter++;

            }
            temperaturChart.YAxis = axis;
            druckChart.YAxis = axis0;

            axis.Title = "°C";
            axis.TitleFont = new Font("Segeo UI", 14F);

            axis0.Title = "[bar]";
            axis0.TitleFont = new Font("Segeo UI", 14F);

            chartControl.LegendsPlacement = ChartPlacement.Outside;
            chartControl.LegendPosition = ChartDock.Bottom;
            chartControl.LegendAlignment = ChartAlignment.Center;
            chartControl.Title.Visible = false;

            ChartAxis chartAxis = new ChartAxis();
            chartAxis.Orientation = ChartOrientation.Horizontal;
            chartAxis.Range = new MinMaxInfo(0, 6, 1);
            chartAxis.DrawGrid = false;
            chartAxis.LineType.Width = 1F;
            chartAxis.LineType.ForeColor = Color.Black;
            chartControl.Axes.Add(chartAxis);

            chartControl.Series.Add(temperaturChart);
            chartControl.Series.Add(druckChart);
            chartControl.Skins = Skins.Metro;


            axis1.OpposedPosition = true;
            axis.EdgeLabelsDrawingMode = ChartAxisEdgeLabelsDrawingMode.Shift;
            axis0.EdgeLabelsDrawingMode = ChartAxisEdgeLabelsDrawingMode.Shift;
            axis1.EdgeLabelsDrawingMode = ChartAxisEdgeLabelsDrawingMode.Shift;

            return chartControl;
        }

        private void btn_create_graph_Click(object sender, EventArgs e)
        {
            Stopwatch watch = new Stopwatch();

            string myPath = Path.Combine(destinationPath, "Trend");
            IEnumerable<string> files = Directory.EnumerateFiles(myPath, "*.csv", SearchOption.AllDirectories);
            
            ChartControl chart = getGraph(files.Last());
            if (chart == null) MessageBox.Show("Konnte CSV nicht finden!");
            else
                chart.SaveImage(Path.Combine(destinationPath, "linerGraph.jpg"));

            watch.Stop();
            MessageBox.Show((watch.ElapsedTicks) + " s");
        }

        private void btn_create_protokol_Click(object sender, EventArgs e)
        {
            Hashtable hashtable = inliner.MakeProtokoll(destinationPath);
            BerichtGen.Options options = new BerichtGen.Options("JUME", "liner_einbau.docx", "./", hashtable, new List<BilderObject>());
            options.ShowDialog();
        }
    }
}
