using Syncfusion.EJ.Export;
using Syncfusion.JavaScript.Web;
using Syncfusion.XlsIO;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace QW2021C.UserFunktionen
{

    public partial class Anmeldung : System.Web.UI.Page
    {

        Helper.wettkampf wettk = new Helper.wettkampf();
        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;

            }

            this.lblOrte.Text = wettk.get_wettkampforte_oneString();
            var index = this.Anmeldegrid.Columns.FindIndex(col => col.Field == "Wettkampf1");
            this.Anmeldegrid.Columns.ElementAt(index).AllowEditing = wettk.ar1;
            var index2 = this.Anmeldegrid.Columns.FindIndex(col => col.Field == "Wettkampf2");
            this.Anmeldegrid.Columns.ElementAt(index2).AllowEditing = wettk.ar2;
            var index3 = this.Anmeldegrid.Columns.FindIndex(col => col.Field == "Wettkampf3");
            this.Anmeldegrid.Columns.ElementAt(index3).AllowEditing = wettk.ar3;
            var index4 = this.Anmeldegrid.Columns.FindIndex(col => col.Field == "Wettkampf4");
            this.Anmeldegrid.Columns.ElementAt(index4).AllowEditing = wettk.ar4;

        }

        protected void OnServer_Batcheditrow(object sender, GridEventArgs e)
        {
            try
            {
                ArrayList changed = ((ArrayList)((Dictionary<String, Object>)e.Arguments["batchChanges"])["changed"]);
                if (changed.Count > 0)
                    GridAction("change", changed, e);

            }
            catch
            {

            }
         
        }

        protected void GridAction(string eventType, ArrayList changed, Syncfusion.JavaScript.Web.GridEventArgs e)
        {
            clsDB db = new clsDB();
            if (eventType == "change")
            {
                na_teilnehmer value = new na_teilnehmer();

                for (var i = 0; i <= changed.Count - 1; i++)
                {
                    Dictionary<string, object> KeyVal = changed[i] as Dictionary<string, object>;

                    foreach (KeyValuePair<string, object> keyvals in KeyVal)
                    {
                        if (keyvals.Key == "Checked")
                            value.ischecked = Convert.ToBoolean(keyvals.Value);
                        if (keyvals.Key == "id_athlete")
                            value.id_athlete = Convert.ToInt32(keyvals.Value);
                    }
                    if (value.ischecked == true)
                        db.Add_Athlet(Session["vereinnr"].ToString(), value.id_athlete, Session["userid"].ToString());
                }

                // Dim update As Orders = order.Where(Function(ord) ord.code = value.code).FirstOrDefault()
                // update.isSelected = value.isSelected
                this.Grid1.DataBind();
                log.insert_entry(2, Convert.ToInt32(Session["UserID"]), "Anmeldungen gespeichert");
            }
        }

        public void Teilnehmer_Doppelklick(object sender, GridEventArgs e)
        {
            Dictionary<string, object> keyVals = e.Arguments["data"] as Dictionary<string, object>;
            log.insert_entry(2, Convert.ToInt32(Session["UserID"]), "Teilnehmer doppelklick");

            foreach (KeyValuePair<string, object> keyval in keyVals)
            {
                if (keyval.Key == "id_athlete")
                {
                    clsDB db = new clsDB();
                    db.Add_Athlet(Session["Vereinnr"].ToString(), Convert.ToInt32(keyval.Value), Session["Userid"].ToString());
                }
            }
        }

        public void onclick(object sender, GridEventArgs e)
        {
           
            //if (e.Arguments["commandType"].ToString()=="W1")
            //{
            //    string a = "";
            //}



            clsDB db1 = new clsDB();
            db1.Get_Tabledata("Select * from applikation", false, true);
            bool W1 = Convert.ToBoolean(db1.dsdaten.Tables[0].Rows[0]["Anmelderunde1"]);
            bool W2 = Convert.ToBoolean(db1.dsdaten.Tables[0].Rows[0]["Anmelderunde2"]);
            bool W3 = Convert.ToBoolean(db1.dsdaten.Tables[0].Rows[0]["Anmelderunde3"]);
            bool W4 = Convert.ToBoolean(db1.dsdaten.Tables[0].Rows[0]["Anmelderunde4"]);
            bool h1 = false;
            bool h2 = false;
            bool h3 = false;
            bool h4 = false;
            int anmeldenr = 0;
            bool notdelete = false;

            Dictionary<string, object> keyVals = e.Arguments["data"] as Dictionary<string, object>;

            foreach (KeyValuePair<string, object> keyval1 in keyVals)
            {
                if (keyval1.Key == "Wettkampf1") h1 = Convert.ToBoolean(keyval1.Value);
                if (keyval1.Key == "Wettkampf2") h2 = Convert.ToBoolean(keyval1.Value);
                if (keyval1.Key == "Wettkampf3") h3 = Convert.ToBoolean(keyval1.Value);
                if (keyval1.Key == "Wettkampf4") h4 = Convert.ToBoolean(keyval1.Value);
                if (keyval1.Key == "Anmeldenr") anmeldenr = Convert.ToInt32(keyval1.Value);
            }

            if (W2 == true && h1 == true) notdelete = true;
            if (W3 == true && (h1 == true || h2 == true)) notdelete = true;
            if (W4 == true && (h1 == true || h2 == true || h3 == true)) notdelete = true;
            if (notdelete == true)
            {
                this.msgDialog.ShowOnInit = true;
                return;
            }



            clsDB db = new clsDB();
            db.Get_Tabeldata_for_Update("Select * from anmeldung where anmeldenr=" + anmeldenr.ToString());
            db.dsdaten.Tables[0].Rows[0]["aktiv"] = 0;
            db.dsdaten.Tables[0].Rows[0]["mutiertam"] = DateTime.Now;
            db.dsdaten.Tables[0].Rows[0]["benutzernr"] = 1;
            db.Update_Tabeldata();
            this.Grid1.DataBind();
            this.Anmeldegrid.DataBind();

        }

        public void onclick1(object sender, GridEventArgs e)
        {

            int anmeldenr = 0;
            Boolean w = false;

            Dictionary<string, object> keyVals = e.Arguments["data"] as Dictionary<string, object>;

            foreach (KeyValuePair<string, object> keyval1 in keyVals)
            {
                if (keyval1.Key == "Anmeldenr") anmeldenr = Convert.ToInt32(keyval1.Value);
                if (keyval1.Key == "Wettkampf1") w = Convert.ToBoolean(keyval1.Value);
            }


            clsDB db = new clsDB();
            db.Get_Tabeldata_for_Update("Select * from anmeldung where anmeldenr=" + anmeldenr.ToString());
            db.dsdaten.Tables[0].Rows[0]["mutiertam"] = DateTime.Now;
            db.dsdaten.Tables[0].Rows[0]["Wettkampf1"] = w;
            db.dsdaten.Tables[0].Rows[0]["benutzernr"] = 1;
            db.Update_Tabeldata();
            this.Anmeldegrid.DataBind();

        }

        [System.Web.Services.WebMethod()]
        public static void SaveData(string daten)
        {
            string a = "";
        }

        [System.Web.Services.WebMethod()]
        public static void DeleteRow(string daten)
        {
            Dictionary<string, object> keyVals = new Dictionary<string, object>();
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            try
            {
                keyVals = serializer.Deserialize<Dictionary<string, object>>(daten);
                foreach (KeyValuePair<string, object> keyval in keyVals)
                {
                    if (keyval.Key == "Anmeldenr")
                    {
                        clsDB db = new clsDB();
                        db.Get_Tabeldata_for_Update("Select * from anmeldung where anmeldenr=" + keyval.Value.ToString());
                        db.dsdaten.Tables[0].Rows[0]["aktiv"] = 0;
                        db.dsdaten.Tables[0].Rows[0]["mutiertam"] = DateTime.Now;
                        db.dsdaten.Tables[0].Rows[0]["benutzernr"] = 1;
                        db.Update_Tabeldata();
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

        protected void btnAlle_Click(object Sender, ButtonEventArgs e)
        {
            clsDB db = new clsDB();
            db.Add_Nicht_angemeldete_Teilnehmer(Session["vereinnr"].ToString(), Session["Userid"].ToString());
            this.Anmeldegrid.DataBind();
            log.insert_entry(2, Convert.ToInt32(Session["UserID"]), "Alle Athleten angemeldet");
        }

        protected void OnServer_Batcheditrow_Anmeldung(object sender, GridEventArgs e)
        {

            ArrayList changed = ((ArrayList)((Dictionary<String, Object>)e.Arguments["batchChanges"])["changed"]);
            if (changed.Count > 0)
                GridAction_Anmeldung("change", changed, e);
        }

        protected void GridAction_Anmeldung(string eventType, ArrayList changed, Syncfusion.JavaScript.Web.GridEventArgs e)
        {
            clsDB db = new clsDB();
            if (eventType == "change")
            {
                clsAnmeldung value = new clsAnmeldung();

                for (var i = 0; i <= changed.Count - 1; i++)
                {
                    Dictionary<string, object> KeyVal = changed[i] as Dictionary<string, object>;

                    foreach (KeyValuePair<string, object> keyvals in KeyVal)
                    {
                        if (keyvals.Key == "Anmeldenr") value.Anmeldenr = Convert.ToInt32(keyvals.Value);
                        if (keyvals.Key == "Wettkampf1") value.Wettkampf1 = Convert.ToBoolean(keyvals.Value);
                        if (keyvals.Key == "Wettkampf2") value.Wettkampf2 = Convert.ToBoolean(keyvals.Value);
                        if (keyvals.Key == "Wettkampf3") value.Wettkampf3 = Convert.ToBoolean(keyvals.Value);
                        if (keyvals.Key == "Wettkampf4") value.Wettkampf4 = Convert.ToBoolean(keyvals.Value);
                       
                    }
                    db.Get_Tabeldata_for_Update("Select * from anmeldung where anmeldenr=" + value.Anmeldenr.ToString(), false, true);
                    db.dsdaten.Tables[0].Rows[0]["Wettkampf1"] = value.Wettkampf1;
                    db.dsdaten.Tables[0].Rows[0]["Wettkampf2"] = value.Wettkampf2;
                    db.dsdaten.Tables[0].Rows[0]["Wettkampf3"] = value.Wettkampf3;
                    db.dsdaten.Tables[0].Rows[0]["Wettkampf4"] = value.Wettkampf4;
                    db.Update_Tabeldata();
                    log.insert_entry(2, Convert.ToInt32(Session["UserID"]), "Anmeldedaten gespeichert");

                }

                // Dim update As Orders = order.Where(Function(ord) ord.code = value.code).FirstOrDefault()
                // update.isSelected = value.isSelected

                this.Grid1.DataBind();
            }
        }

        protected void FlatGrid_ServerExcelExporting(object sender, Syncfusion.JavaScript.Web.GridEventArgs e)

        {
            //clsDB db = new clsDB();
            //db.Get_Tabledata("Select * from anmeldung", false, true);


            //ExcelExport exp = new ExcelExport();
            //exp.Export((DataTable)db.dsdaten.Tables[0].AsDataView();

            ////exp.Export(Anmeldegrid.Model, (IEnumerable)Anmeldegrid.DataSource, "Export.xlsx", ExcelVersion.Excel2010, true, true, "flat-lime");
            //exp.Export()

        }

        protected void Button1_Click(object Sender, ButtonEventArgs e)
        {
            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 db = new clsDB();
                db.Get_Tabledata(1, Session["vereinnr"].ToString(), Convert.ToInt32(Session["UserID"]));

                DataTable dataTable = db.dsdaten.Tables[0];
                worksheet.ImportDataTable(dataTable, true, 1, 1);
                worksheet.UsedRange.AutofitColumns();

                //Save the workbook to disk in xlsx format
                string targetFolder = HttpContext.Current.Server.MapPath("~/Downloads");
                this.Button1.Enabled = false;
                string excelname = "";
                string dataname = "";
                excelname = DateTime.Now.ToString("ddMMyyyyHHmmss") + "_";
                dataname = DateTime.Now.ToString("ddMMyyyyHHmmss") + "_";
                excelname = excelname + "Exceldata.xlsx";
                dataname = dataname + "XMLData.xml";
                this.HiddenField1.Value = excelname;

                workbook.SaveAs(targetFolder + "\\" + excelname);
                workbook.Close();
                this.HyperLink1.NavigateUrl = "~/Administration/Downloader.aspx?fn=" + excelname;
                this.HyperLink1.Target = "_blank";
                this.HyperLink1.Text = "Download";
                this.HyperLink1.Visible = true;

                this.HyperLink2.NavigateUrl = "~/Reporting/Reporting.aspx";
                this.HyperLink2.Target = "_blank";
                this.HyperLink2.Text = "PDF-Report";
                this.HyperLink2.Visible = true;
                db.dsdaten.WriteXml(targetFolder + "\\" + dataname);
                Session["Reportname"] = "Vereinanmeldung.frx";
                Session["xmldata"] = dataname;
                log.insert_entry(2, Convert.ToInt32(Session["UserID"]), "Anmeldedaten exportiert");

            }
        }

        private void DownloadFile(string filename, string filepath)
        {
            WebClient mywc = new WebClient();
            mywc.DownloadFile(filename, filepath);
            //Response.AddHeader("Content-disposition", "attachment; filename=" + filename) ;
            //Response.ContentType = "application/octet-stream";
            //Response.WriteFile(filepath);
            //Response.End();

        }

        protected void Button3_Click(object Sender, ButtonEventArgs e)
        {
            string targetFolder = HttpContext.Current.Server.MapPath("~/Downloads");
            Response.ContentType = "Application/pdf";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + this.HiddenField1.Value);
            Response.TransmitFile(targetFolder + "\\" + this.HiddenField1.Value);
            Response.End();
        }

        protected void Button2_Click(object Sender, ButtonEventArgs e)
        {
            this.Label1.Text = "";
            this.Button1.Enabled = false;
            clsDB db = new clsDB();
            DataTable paramdaten = new DataTable();
            DataRow dbr = paramdaten.NewRow();

            paramdaten.Columns.Clear();
            paramdaten.Rows.Clear();


            dbr = paramdaten.NewRow();
            paramdaten.Columns.Add("Paramname");
            paramdaten.Columns.Add("Paramvalue");

            dbr[0] = "@VereinNr";
            dbr[1] = Session["Vereinnr"].ToString();
            paramdaten.Rows.Add(dbr);
            dbr = paramdaten.NewRow();
            db.Get_Tabledata("chk_gruppe", "", "", "", true, paramdaten);
            if (db.dsdaten.Tables[0].Rows.Count > 0)
            {
                Label1.Text = "Teilnehmer ohne Wettkamp-Zuordnung vorhanden. Bitte prüfen";
                Helper.MessageBox.Show("Teilnehmer ohne Wettkamp-Zuordnung vorhanden. Bitte prüfen.");
            }
            else
            {
                this.Button1.Enabled = true;
                Helper.MessageBox.Show("Prüfung der Anmeldungen war erfolgreich.");
            }
            log.insert_entry(2, Convert.ToInt32(Session["UserID"]), "Teilnehmerprüfung druchgeführt");
            
        }

        protected void closebtn_Click(object sender, EventArgs e)
        {

           
        }

        protected void btn1_Click(object Sender, ButtonEventArgs e)
        {
            this.msgDialog.ShowOnInit = false;
        }

        protected void Anmeldegrid_ServerRecordClick(object sender, GridEventArgs e)
        {
            string a = "";
        }

        protected void Anmeldegrid_ServerEditRow(object sender, GridEventArgs e)
        {
            string a = "";
        }
    }


    public class na_teilnehmer
    {
        public bool ischecked { get; set; }
        public int id_athlete { get; set; }
        public string license { get; set; }
        public string lastname { get; set; }
        public string firstname { get; set; }
        public string birth_date { get; set; }
        public string sex { get; set; }
        public string nationality { get; set; }
        public string License_cat { get; set; }
        public string license_paid { get; set; }
    }

    public class clsAnmeldung
    {
        public int Anmeldenr { get; set; }

        public string Lizenznr { get; set; }

        public string bez { get; set; }

        public string Name { get; set; }

        public string Vorname { get; set; }

        public string GebDat { get; set; }

        public string Geschlecht { get; set; }

        public string Kategorie { get; set; }

        public string Nationalitaet { get; set; }

        public string VereinNr { get; set; }

        public bool Wettkampf1 { get; set; }

        public bool Wettkampf2 { get; set; }

        public bool Wettkampf3 { get; set; }

        public bool Wettkampf4 { get; set; }

        public DateTime Mutiertam { get; set; }

        public string BenutzerNr { get; set; }

        public bool aktiv { get; set; }

        public int mantlnr { get; set; }

        public int Mannschaftnralt_sik { get; set; }

        public string Mannschaftsnr1 { get; set; }

        public string Mannschaftsnr2 { get; set; }

        public string Mannschaftsnr3 { get; set; }

        public string Mannschaftsnr4 { get; set; }

        public int Mannschaftnralt1 { get; set; }

        public int Mannschaftnralt2 { get; set; }

        public int Mannschaftnralt3 { get; set; }

        public int Mannschaftnralt4 { get; set; }

        public string mannschaftsnr { get; set; }

    }



}