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
{
    /// <summary>
    /// 
    /// </summary>
    public partial class UCInliner : UserControl
    {
        enum TabPages
        {
            VORRAUSSETZUNGEN = 0,
            LINERGRUNDLAGEN
        }
        InlinerSanierung inliner = null;
        string destinationPath = string.Empty;
        UCLinerGrundlagen UCLinerGrundlagen = null;
        List<string> filenames = new List<string>();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="san"></param>
        public UCInliner(InlinerSanierung san)
        {
            InitializeComponent();
            inliner = san;
            UCLinerGrundlagen = new UCLinerGrundlagen(san);

            TabPage tab = new TabPage("Linergrundlagen");
            UCLinerGrundlagen.Dock = DockStyle.Fill;
            tab.Controls.Add(UCLinerGrundlagen);
            tabControl1.TabPages.Add(tab);
        }

        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:
                     
                    
                    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)
            {
                if (inliner.Datum <= DateTime.MinValue || inliner.Datum >= DateTime.MaxValue)
                    inliner.Datum = new DateTime(2018, 01, 01, 12, 0, 0);
            }
            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);
            string message = "";
            double temperatur = temperature.GetTemperatur(out message);
            inliner.TempAusen = temperatur;

            if (!message.Equals("")) MessageBox.Show(message);

            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);
                    newClient.DeleteFile(file);

                }
                MessageBox.Show("Daten wurden heruntergeladen und von der Anlage gelöscht", "Fertig", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (TimeoutException ex)
            {
                MessageBox.Show("Die anlage reagiert nicht!\n"+ex.Message);
            }

        }

        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!, Bitte beachten Sie, dass das fenster einfrieren kann", "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 static ChartControl getGraph(List<UVcsvStrukture> input)
        {
            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);
            
            int counter = 0;
            
            foreach (UVcsvStrukture pars in input)
            {
                temperaturChart.Points.Add(counter, pars.Temperatur);
                druckChart.Points.Add(counter, pars.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 bool AccessCSV()
        {
            string myPath = Path.Combine(destinationPath, "Trend");
            if (!Directory.Exists(myPath))
                return false;

            IEnumerable<string> files = Directory.EnumerateFiles(myPath, "*.csv", SearchOption.AllDirectories);

            List<UVcsvStrukture> struktures = HelpFunktion.ParseCSVFile(files.Last());

            inliner.AnfangAushaertung = struktures.Select(x => x.Zeitstempel).Min();
            inliner.EndeAushaertung = struktures.Select(x => x.Zeitstempel).Max();
            ChartControl chart = getGraph(struktures);
            if (chart == null) return false;
            else
                chart.SaveImage(Path.Combine(destinationPath, "linerGraph.jpg"));
            return true;
        }

        private void btn_create_protokol_Click(object sender, EventArgs e)
        {
            if(!AccessCSV())
            {
                MessageBox.Show("Warnung, es wurden keine Daten von der Anlage geladen, Grafik konnte nicht erstellt werden");
            }
            Hashtable hashtable = inliner.MakeProtokoll(destinationPath);
            DirectoryInfo directory = Directory.GetParent(destinationPath);
            string speicherpfad = directory.FullName;
            BerichtGen.FrmOptions options = new BerichtGen.FrmOptions("JUME", "liner_einbau.docx", speicherpfad,inliner.Inspektionsobjekt.Objektbezeichnung, hashtable, new List<BilderObject>());
            options.ShowDialog();
        }
    }
}
