using GenericParsing;
using QW2021C.Helper;
using Syncfusion.XlsIO;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace QW2021C.Administration
{
    public partial class Wettkampfeinteilung : System.Web.UI.Page
    {
        Helper.Log log = new Helper.Log();

        protected void Page_Load(object sender, EventArgs e)
        {
            //try
            //{
            //    if (Session["LoggedIn"].ToString() == "False")
            //    {
            //        Response.Redirect("~/default.aspx");
            //        return;
            //    }
            //}
            //catch
            //{
            //    Response.Redirect("~/default.aspx");
            //    return;

            //}
            //if (Page.IsPostBack == true)
            //{
            //    // if (this.Tab1.SelectedItemIndex == 1) this.target.Visible = true;

            //    return;
            //}

        }

        protected void Upload1_Complete(object sender, Syncfusion.JavaScript.Web.UploadBoxCompleteEventArgs e)
        {
            log.insert_entry(2, Convert.ToInt32(Session["UserID"]), "Datei-Upload erfolgreich " + e.Name);
            this.Tab1.SelectedItemIndex = 1;
            //this.target.Visible = true;
            this.HiddenField1.Value = e.Name;

        }

        protected void ButtonVerarbeiten1_Click(object Sender, Syncfusion.JavaScript.Web.ButtonEventArgs e)
        {
            string filename = this.HiddenField1.Value;
            string targetFolder = HttpContext.Current.Server.MapPath("~/Upload");
            filename = targetFolder + "\\" + filename;
            GenericParserAdapter Parser = new GenericParserAdapter(filename);
            DataSet dsresult = new DataSet();
            Parser.ColumnDelimiter = Convert.ToChar(";");
            dsresult = Parser.GetDataSet();

            List<Gruppencounter> Gruppenzaehler = new List<Gruppencounter>();

            string gruppe = "";
            string Kategorie = "";
            string GruppeNr = "";
            string Startzeit = "";
            string gruppealt = "";
            string Kanton = "";
            string KidID = "";
            clsDB db = new clsDB();
            db.Get_Tabledata("Select * from kat where kidcup=1", false, true);
            DataSet kidcup = new DataSet();
            kidcup.Tables.Add(db.dsdaten.Tables[0].Copy());
            db.dsdaten.Tables.Clear();

            db.Get_Tabeldata_for_Update("Select sqlscript from  SQLQueries where sqlscriptnumber=2", false, true);
            string sql = db.dsdaten.Tables[0].Rows[0][0].ToString();
            db.dsdaten.Tables.Clear();
            DataTable resdata = new DataTable();
            db.Get_Tabledata(sql, false, true);
            resdata = db.dsdaten.Tables[0].Copy();
            resdata.Rows.Clear();
            db.dsdaten.Tables.Clear();

            foreach (DataRow r in dsresult.Tables[0].Rows)
            {
                if (r[4].ToString().IndexOf("Kategorie") > -1)
                {
                    Kategorie = r[4].ToString();
                    Kategorie = Kategorie.Substring(9, Kategorie.Length - 9);
                    Kategorie = Kategorie.Trim();
                }
                if (r[3].ToString().IndexOf("Gr.") > -1)
                {
                    gruppe = r[3].ToString();
                    GruppeNr = r[8].ToString();
                    Startzeit = r[9].ToString();

                    if (gruppe != gruppealt)
                    {
                        gruppealt = gruppe;
                        Gruppenzaehler.Add(new Gruppencounter(gruppe, 0));
                    }
                    //else
                    //{
                    //    foreach (Gruppencounter g in Gruppenzaehler)
                    //    {
                    //        if (g.Gruppe.ToString() == gruppe) g.Counter = g.Counter + 1;
                    //    }
                    //}
                }
                if (r[6].ToString() != "" && r[6].ToString() != "Lizenz-Nr.")
                {
                    db.dsdaten.Tables.Clear();
                    db.Get_Tabledata(sql + " where lizenznr='" + r[6].ToString() + "'", false, true);
                    if (db.dsdaten.Tables[0].Rows.Count > 0)
                    {
                        foreach (Gruppencounter g in Gruppenzaehler)
                        {
                            if (g.Gruppe.ToString() == gruppe) g.Counter = g.Counter + 1;
                        }
                        DataRow nr = resdata.NewRow();

                        foreach (DataColumn c in db.dsdaten.Tables[0].Columns)
                        {
                            nr[c.ColumnName] = db.dsdaten.Tables[0].Rows[0][c.ColumnName];
                        }
                        nr["GruppeNr"] = GruppeNr;
                        nr["GruppeName"] = gruppe;
                        nr["Startzeit"] = Startzeit;

                        bool usekidid = false;
                        DataRow krow = resdata.NewRow();
                        foreach (DataRow kr in kidcup.Tables[0].Rows)
                        {
                            if (kr["Kategorie"].ToString() == nr["Kategorie"].ToString())
                            {


                                krow.ItemArray = nr.ItemArray;
                                krow["Bewerb"] = "UKC";
                                usekidid = true;
                                break;
                            }
                        }
                        if (usekidid == true)
                        {
                           
                            nr["KidID"] = "";

                        }
                        if (this.chkukc.Checked == false) usekidid = false;
                        resdata.Rows.Add(nr);
                        if (usekidid==true)
                        { 
                            resdata.Rows.Add(krow); 
                        }


                    }

                }

            }
            using (ExcelEngine excelEngine = new ExcelEngine())
            {
                //Initialize Application
                IApplication application = excelEngine.Excel;

                //Set the default application version as Excel 2016
                application.DefaultVersion = ExcelVersion.Excel2016;

                //Create a new workbook
                IWorkbook workbook = application.Workbooks.Create(1);

                //Access first worksheet from the workbook instance
                IWorksheet worksheet = workbook.Worksheets[0];

                //Exporting DataTable to worksheet
                clsDB db1 = new clsDB();

                worksheet.ImportDataTable(resdata, true, 1, 1);
                worksheet.UsedRange.AutofitColumns();

                string excelname = "";
                excelname = DateTime.Now.ToString("ddMMyyyyHHmmss") + this.HiddenField1.Value;
                excelname = Path.GetFileNameWithoutExtension(excelname) + ".csv";
                excelname = excelname.Replace(" ", "_");
                targetFolder = HttpContext.Current.Server.MapPath("~/Downloads");

                workbook.SaveAs(targetFolder + "\\" + excelname, ";", System.Text.Encoding.UTF8);
                workbook.Close();

                //Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenExcel", "window.open(\"~/Downloads/Output.xlsx\");", true);
                //DownloadFile("Output.xlsx", targetFolder + "\\Output.xlsx");
                this.Download.NavigateUrl = "~/Administration/Downloader.aspx?fn=" + excelname;
                this.Download.Target = "_blank";
                this.Download.Text = "Download";
                this.Download.Visible = true;
                this.Tab1.SelectedItemIndex = 2;
                log.insert_entry(2, Convert.ToInt32(Session["UserID"]), "Export Einteilung:" + excelname);
                log.insert_entry(2, Convert.ToInt32(Session["UserID"]), sql);
                this.lblzusammenfassung.Text = "";
                foreach (Gruppencounter g in Gruppenzaehler)
                {
                    this.lblzusammenfassung.Text += g.Gruppe.ToString() + ": " + g.Counter.ToString() + "<br>";
                    if (g.Gruppe == gruppe) g.Counter = g.Counter + 1;
                }


            }
        }




    }
    public class Gruppencounter
    {
        public Gruppencounter(string Gruppe, int counter)
        {
            this.Gruppe = Gruppe;
            this.Counter = counter;
        }
        public string Gruppe { get; set; }
        public int Counter { get; set; }
    }
}