using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace Consulenza.Web
{
    public partial class TestAnd : System.Web.UI.Page
    {
        ConsulenzaUnicaWS.ReportManager reportManager = new ConsulenzaUnicaWS.ReportManager();

        protected void CreateReport_Click(object sender, EventArgs e)
        {          
            
            reportManager.Timeout = 1000 * 60 * 10;
            
            imagePdf = reportManager.CreaReport(
                    codiceAgente.Text,
                    codiceFiscale.Text,
                    codiceMandato.Text,
                    codiceRete.Text,
                    long.Parse(chiave.Text.Trim().Equals("")?"0":chiave.Text.Trim()), 
                    new ConsulenzaUnicaWS.Template { 
                        IdModello = -1,
                        Nome = Moktemplate.Text
                    },
                    new ConsulenzaUnicaWS.Parametro[0]
                );
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment; filename=TheDocument.pdf");
                Response.ContentType = "application/pdf";
                Response.BinaryWrite(imagePdf);
                Response.Flush();
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            codiceAgente.Text="006803";
            codiceFiscale.Text="BNCRRT34C30D612C";
            codiceMandato.Text = "";
            codiceRete.Text="F";
            Moktemplate.Text = "andread";
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            codiceAgente.Text = "012057";
            codiceFiscale.Text = "DNDMCL54A11L551Z";
            codiceMandato.Text = "";
            codiceRete.Text = "F";

            
        }
        protected void Button3_Click(object sender, EventArgs e)
        {
            codiceAgente.Text = "002317";
            codiceFiscale.Text = "PCCRNN46B08L682D";
            codiceMandato.Text = "";
            codiceRete.Text = "F";
        }
        protected void Button4_Click(object sender, EventArgs e)
        {
            codiceAgente.Text = "002317";
            codiceFiscale.Text = "PRZRNZ44S14B025B";
            codiceMandato.Text = "";
            codiceRete.Text = "F";
        }
        protected void Button5_Click(object sender, EventArgs e)
        {
            codiceAgente.Text = "008510";
            codiceFiscale.Text = "SPSPQL72T21F839Y";
            codiceMandato.Text = "";
            codiceRete.Text = "F";
        }
        protected void Button6_Click(object sender, EventArgs e)
        {
            codiceAgente.Text = "008521";
            codiceFiscale.Text = "MTLNZE60P14E463F";
            codiceMandato.Text = "";
            codiceRete.Text = "S";
        }
        protected void Button9_Click(object sender, EventArgs e)
        {
            codiceAgente.Text = "002317";
            codiceFiscale.Text = "ZZLDRN51E10B025O";
            codiceMandato.Text = "";
            codiceRete.Text = "F";
        }

        protected void Button7_Click(object sender, EventArgs e)
        {
            codiceAgente.Text = "012057";
            codiceFiscale.Text = "";
            codiceMandato.Text = "";
            codiceRete.Text = "F";
            chiave.Text = "23056";
            Moktemplate.Text = "andrean";
        }
        protected void Button8_Click(object sender, EventArgs e)
        {
            codiceAgente.Text = "012057";
            codiceFiscale.Text = "";
            codiceMandato.Text = "";
            codiceRete.Text = "F";
            chiave.Text = "38030";
            Moktemplate.Text = "andrean";
        }

        protected void Button10_Click(object sender, EventArgs e)
        {
            codiceAgente.Text = "012057";
            codiceFiscale.Text = "NGLMRC74C26A182E";
            codiceMandato.Text = "";
            codiceRete.Text = "F";
            Moktemplate.Text = "andream";
        }

        protected void Button11_Click(object sender, EventArgs e)
        {
            codiceAgente.Text = "006803";
            codiceFiscale.Text = "BCHRRT54L12G999R";
            codiceMandato.Text = "";
            codiceRete.Text = "F";
            chiave.Text = "9254151";
            Moktemplate.Text = "andreap";
        }
        protected void CreateReportPO_Click(object sender, EventArgs e)
        {

            reportManager.Timeout = 1000 * 60 * 10;
            imagePdf = reportManager.CreaReportPO(
                    codiceAgente.Text, 
                    codiceFiscale.Text,
                    codiceMandato.Text,
                    codiceRete.Text,
                    long.Parse(chiave.Text)                    
                );

            Response.Clear();
            Response.AddHeader("Content-Disposition", "attachment; filename=TheDocument.pdf");
            Response.ContentType = "application/pdf";
            Response.BinaryWrite(imagePdf);
            Response.Flush();

        }
        protected void butGeneraPdf_Click(object sender, EventArgs e)
        {
            


            //ConsulenzaUnicaWS.Template template = new ConsulenzaUnicaWS.Template();
            //long ChiaveClientePb = long.Parse(txtchiave.Text);
            //template.IdModello = -1;
            //template.Nome = txtmessage.Text;
            //ConsulenzaUnicaWS.Parametro[] parametri = new ConsulenzaUnicaWS.Parametro[0];
            //reportManager.Timeout = 1000 * 60 * 10;
            //imagePdf = reportManager.CreaReportOld(ChiaveClientePb, template, parametri);


            //Response.Clear();
            //Response.AddHeader("Content-Disposition", "attachment; filename=TheDocument.pdf");
            //Response.ContentType = "application/pdf";
            //Response.BinaryWrite(imagePdf);
            //Response.Flush();

        }  
        protected void Page_Load(object sender, EventArgs e)
        {
           
            if (!IsPostBack)
            {
                hModelliTemplate.Value = "0px";
                hDocumenti.Value = "0px";
                var listmodelli = reportManager.GetModelli();

                var modelli = (from ConsulenzaUnicaWS.Modello temp in listmodelli
                               select new
                               {
                                   temp.Id,
                                   temp.Nome,
                                   temp.Rete,
                                   Options = string.Join(",", (from ConsulenzaUnicaWS.Option ops in temp.Options select ops.Key + "=" + ops.Value))
                               }).ToList();

                gwModelli.DataSource = modelli;
                gwModelli.DataBind();
            }

        }
        protected void gwModelli_SelectedIndexChanged(object sender, EventArgs e)
        {
            int idModello = int.Parse(gwModelli.Rows[gwModelli.SelectedIndex].Cells[1].Text);
            string codicePb = txtCodicePb.Text;

            ConsulenzaUnicaWS.Modello modello = reportManager.GetModello(idModello, codicePb);

            var modelloSchede = (from ConsulenzaUnicaWS.Scheda temp in modello.Schede
                                 select new
                                 {
                                     temp.Id,
                                     temp.NomeImmagine,
                                     temp.NumTab,
                                     TitoloTab = string.Join(",", (from ConsulenzaUnicaWS.Tabs tabs in modello.Tabs where tabs.NumTab == temp.NumTab select tabs.Titolo)),
                                     temp.Sezioni,
                                     temp.TestoHTML,
                                     Vincoli = string.Join(",", (from ConsulenzaUnicaWS.Vincolo ops in temp.Vincoli select ops.Key + "=" + ops.Value)),
                                     Options = string.Join(",", (from ConsulenzaUnicaWS.Option ops in temp.Options select ops.Key + "=" + ops.Value))
                                 }).ToList();

            gwSchedeModello.DataSource = modelloSchede;
            gwSchedeModello.DataBind();

            var templates = (from ConsulenzaUnicaWS.Template temp in modello.Templates
                             select new
                             {
                                 temp.Id,
                                 temp.CodicePb,
                                 temp.IdModello,
                                 temp.IsDefault,
                                 temp.Nome,
                                 Options = string.Join(",", (from ConsulenzaUnicaWS.Option ops in temp.Options select ops.Key + "=" + ops.Value))
                             }).ToList();



            gwTemplate.DataSource = templates;
            gwTemplate.DataBind();
            gwTemplate.SelectedIndex = -1;


            gwSchedeTemplate.DataSource = new System.Data.DataTable();
            gwSchedeTemplate.DataBind();
        }
        protected void gwTemplate_SelectedIndexChanged(object sender, EventArgs e)
        {
            int idTemplate = int.Parse(gwTemplate.Rows[gwTemplate.SelectedIndex].Cells[1].Text);
            string isDefault = gwTemplate.Rows[gwTemplate.SelectedIndex].Cells[4].Text;
            txtIdTemplate.Text = idTemplate.ToString();
            txtIsDefault.Text = isDefault;
            txtNomeTamplate.Text = gwTemplate.Rows[gwTemplate.SelectedIndex].Cells[5].Text;
            ConsulenzaUnicaWS.SchedaTemplate[] schedeTemplate = reportManager.GetSchedeTemplate(idTemplate, isDefault);

            var _schedeTemplate = (from ConsulenzaUnicaWS.SchedaTemplate temp in schedeTemplate
                                   select new
                                   {
                                       temp.Id,
                                       Options = string.Join(",", (from ConsulenzaUnicaWS.Option ops in temp.Options select ops.Key + "=" + ops.Value))
                                   }).ToList();


            gwSchedeTemplate.DataSource = _schedeTemplate;
            gwSchedeTemplate.DataBind();
        }
        protected void butSalvaTemplate_Click(object sender, EventArgs e)
        {
            int idModello = int.Parse(gwModelli.Rows[gwModelli.SelectedIndex].Cells[1].Text);
            string codicePb = txtCodicePb.Text;
            string nomeTamplate = txtNomeTamplate.Text;
            int idTemplate = int.Parse(txtIdTemplate.Text);
            string isDefault = txtIsDefault.Text.Trim();          
            

            ConsulenzaUnicaWS.Template template = reportManager.GetTemplate(idTemplate, isDefault);

            


            reportManager.SetTemplate(idModello, codicePb, nomeTamplate, template.Options, template.Schede);
        }
        protected void butCancellaTemplate_Click(object sender, EventArgs e)
        {
            if (txtIsDefault.Text.Trim().Equals("N"))
            {
                int idTemplate = int.Parse(txtIdTemplate.Text);
                int ris = reportManager.DelTemplate(idTemplate);
            }
        }
        private byte[] imagePdf = new byte[0];
      
        protected void butSalvaPdf_Click(object sender, EventArgs e)
        {
            int idTemplate = int.Parse(txtIdTemplate.Text);
            string isDefault = txtIsDefault.Text.Trim();
            long ChiaveClientePb = long.Parse( txtChiaveClientePb.Text);
            int idModello = int.Parse(gwModelli.Rows[gwModelli.SelectedIndex].Cells[1].Text);
            string codicePb = txtCodicePb.Text;

            if (imagePdf.Length > 0)
            {
                ConsulenzaUnicaWS.Template template = reportManager.GetTemplate(idTemplate, isDefault);

                List<ConsulenzaUnicaWS.Cliente> clienti = new List<ConsulenzaUnicaWS.Cliente>();
                ConsulenzaUnicaWS.Cliente cliente = new ConsulenzaUnicaWS.Cliente();
                cliente.ChiaveClientePb = ChiaveClientePb;
                clienti.Add(cliente);

                ConsulenzaUnicaWS.DocumentoPdf doc = new ConsulenzaUnicaWS.DocumentoPdf
               {
                   //IdPdf = null,
                   IdModello = idModello,
                   IdStato = "P",
                   IdArchivio = "O",
                   CodicePB = codicePb,
                   Image = imagePdf,
                   Note = txtNomeTamplate.Text,
                   Clienti = clienti.ToArray(),
                   ChiaveNucleo = 0,

               };
                doc.IdPdf = reportManager.SetDocumentPdf(doc, "S");
                imagePdf = new byte[0];
            }
        }

        protected void butCercaPdf_Click(object sender, EventArgs e)
        {
             
            long idPdf = long.Parse(txtIdPdf.Text);

            ConsulenzaUnicaWS.DocumentoPdf documentoPdf = reportManager.GetPdf(idPdf);
            if (documentoPdf.IdPdf > 0)
            {
                List<ConsulenzaUnicaWS.DocumentoPdf> ldocpdf = new List<ConsulenzaUnicaWS.DocumentoPdf>();
                ldocpdf.Add(documentoPdf);
                var doc = (from ConsulenzaUnicaWS.DocumentoPdf temp in ldocpdf
                           select new
                           {
                               temp.IdPdf,
                               temp.IdModello,
                               temp.IdStato,
                               temp.IdArchivio,
                               temp.CodicePB,
                               temp.dtCreazione,
                               temp.Note,                               
                               isImage = temp.Image == null ? "N" : temp.Image.Length == 0 ? "N" : "S",
                               temp.ChiaveNucleo,
                               Clienti_CodiceContratto = string.Join(";", (from ConsulenzaUnicaWS.Cliente cliente in temp.Clienti select "[" + cliente.ChiaveClientePb.ToString() + "," + cliente.CodiceContratto + ","+cliente.ChiaveProposta+","+cliente.PropostaBase+"]"))
                           }).ToList();

                gwDocumentoPdf.DataSource = doc;

                
            }
            else {
                gwDocumentoPdf.DataSource = new System.Data.DataTable();
            }

            gwDocumentoPdf.DataBind();
            txtGetLog_Click(null, null);
            Panel6.Height = 60;
            Panel5.Height = 300;
            lbnumdoc.Text = " ";
            
             
        }
        protected void butCercaTuttiPdf_Click(object sender, EventArgs e)
        {
            //long idPdf = long.Parse(txtIdPdf.Text);
            ConsulenzaUnicaWS.RicercaPdf ricercaPdf = new ConsulenzaUnicaWS.RicercaPdf();
            if(txtIdPdf.Text!="") ricercaPdf.IdPdf=long.Parse(txtIdPdf.Text);
            if(trIdProvenienza.Text!="") ricercaPdf.IdProvenienza = trIdProvenienza.Text;
            ricercaPdf.IdModello = new int[1]; 
            if(trIdModello.Text!="") ricercaPdf.IdModello[0] = int.Parse(trIdModello.Text);
            if(trIdStato.Text!="") ricercaPdf.IdStato = trIdStato.Text;
            if(trIdArchivio.Text!="") ricercaPdf.IdArchivio =trIdArchivio.Text;
            if(trCodicePb.Text!="") ricercaPdf.CodicePb =trCodicePb.Text;
            if(trDtInizio.Text!="") ricercaPdf.DtInizio =DateTime.Parse(trDtInizio.Text) ;
            if (trDtFine.Text != "") ricercaPdf.DtFine = DateTime.Parse(trDtFine.Text);
            if(trChiaveNucleo.Text!="") ricercaPdf.ChiaveNucleo = long.Parse(trChiaveNucleo.Text);
            if(trChiaveClientePb.Text!="") ricercaPdf.ChiaveClientePb =int.Parse(trChiaveClientePb.Text);
            if (trCodiceContratto.Text != "") ricercaPdf.CodiceContratto = trCodiceContratto.Text;

          
  
            
            ConsulenzaUnicaWS.DocumentoPdf[] documentoPdf = reportManager.GetPdfs(ricercaPdf);
            var doc = (from ConsulenzaUnicaWS.DocumentoPdf temp in documentoPdf
                       select new
                       {
                           temp.IdPdf,
                           temp.IdModello,
                           //temp.IdStato,
                           //temp.IdArchivio,
                           //temp.CodicePB,
                           //temp.dtCreazione,
                           //temp.Note,                        
                           temp.ChiaveNucleo,
                           //Clienti_CodiceContratto = string.Join(";", (from ConsulenzaUnicaWS.Cliente cliente in temp.Clienti select "[" + cliente.ChiaveClientePb.ToString() + "," + cliente.CodiceContratto + ","+cliente.ChiaveProposta+","+cliente.PropostaBase+"]"))
                       }).ToList();

            gwDocumentoPdf.DataSource = doc;
            gwDocumentoPdf.DataBind();
            gwPdf.DataSource = new System.Data.DataTable();
            gwPdf.DataBind();
            Panel6.Height = 400;
            Panel5.Height = 60;
            lbnumdoc.Text = " " + doc.Count;
        }

        protected void txtGetLog_Click(object sender, EventArgs e)
        {
            if (txtIdPdf.Text != "")
            {
                long idPdf = long.Parse(txtIdPdf.Text);

                ConsulenzaUnicaWS.LogPdf[] logPdf = reportManager.GetlogPdf(idPdf);

                gwPdf.DataSource = logPdf;
                gwPdf.DataBind();
                Panel5.Height = 300;
            }
        }
       

        protected void butGetImage_Click(object sender, EventArgs e)
        {
            long idPdf = long.Parse(txtIdPdf.Text);

            ConsulenzaUnicaWS.DocumentoPdf documentoPdf = reportManager.GetPdf(idPdf);


            byte[] imagePdf = documentoPdf.Image;

            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.BinaryWrite(imagePdf);
            Response.Flush();
        }

        
        //SetStato fare
        protected void txtCerca_Click(object sender, EventArgs e)
        {
            long idPdf = long.Parse(txtIdPdf.Text);
            ConsulenzaUnicaWS.RicercaPdf ricercaPdf = new ConsulenzaUnicaWS.RicercaPdf();
            ricercaPdf.IdPdf = idPdf;
            //ricercaPdf.DtInizio = new DateTime(2015, 8,10);
            //ricercaPdf.DtFine = new DateTime(2015, 8, 10);
            ConsulenzaUnicaWS.DocumentoPdf[] documentoPdf = reportManager.GetPdfs(ricercaPdf);
            gwPdf.DataSource = documentoPdf;
            gwPdf.DataBind();
        }

        //protected void butStato_Click(object sender, EventArgs e)
        //{
        //    long idPdf = long.Parse(txtIdPdf.Text);
        //    string idStato = txtStato.Text;
        //    int risp = reportManager.SetStato(idPdf, idStato, "S");
        //}

        protected void butVincoli_Click(object sender, EventArgs e)
        {
            ConsulenzaUnicaWS.ReportManager reportManager = new ConsulenzaUnicaWS.ReportManager();

            List<ConsulenzaUnicaWS.Scheda> schede = new List<ConsulenzaUnicaWS.Scheda>();
            foreach (ConsulenzaUnicaWS.Modello modello in reportManager.GetModelli())
            {
               
                foreach(var  s in from m in reportManager.GetModello(modello.Id, "").Schede select m){
                    if(!schede.Exists(o=>o.Id==s.Id)){
                        schede.Add(s);
                    }
                }
                 

            }

           


            
            long ccpb = long.Parse(ChiaveClientePb.Text);

           List<ConsulenzaUnicaWS.Vincolo> vinc = reportManager.GetVincoli(ccpb, 0, "Diagnosi").ToList();
           foreach (var v in  reportManager.GetVincoli(ccpb, 0, "Monitoragio").ToList())
            {
              
                if (!vinc.Exists(o => o.Key == v.Key))
                {
                    vinc.Add(v);
                }
            }
           foreach (var v in reportManager.GetVincoli(ccpb, 0, "Nucleo").ToList())
           {

               if (!vinc.Exists(o => o.Key == v.Key))
               {
                   vinc.Add(v);
               }
           }
          

           // var vinc = from o in vd.Union(vm).Union(vn) where o.Value == "0" select o;
           
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("IdScheda") { });
            dt.Columns.Add(new DataColumn("Vincoli") { });
            dt.Columns.Add(new DataColumn("Opzioni") { });



            foreach (var s in from o in schede  orderby o.Id select o )
            {
                bool ins = false;
                DataRow dr = dt.NewRow();
                dr[0] = s.Id;
                dr[1] = "";
                dr[2] = "";                
                
                foreach (var sv in s.Vincoli) {
                    foreach (var v in from o in vinc select o) {
                        if (v.Key == sv.Key) {
                            dr[1] = v.Key;
                            ins = true;
                        }
                    }
                }
                foreach (var ps in s.Options)
                {
                    foreach (var v in from o in vinc select o)
                    {
                        string value = ps.Value;

                        int a = value.IndexOf("\"vincoli\":[\"") + 12;
                        if (a > 12)
                        {
                            int b = value.IndexOf("\"]", a) - a;
                            value = value.Substring(a);
                        }
                        else value = "";


                        if (value.Contains(v.Key))
                        {
                            dr[2] += " " + ps.Key +"."+v.Key;
                            ins = true;
                        }
                    }
                }
                if(ins)
                 dt.Rows.Add(dr);
            }


            //foreach (var v in from o in vinc select o)
            //{
            //    DataRow dr =  dt.NewRow(); 
            //    dr[0] = v.Key;
            //    dr[1] = v.Value;
            //    dr[2] = "";
            //    dr[3] = "";
            //    foreach (var s in schede)
            //    {
            //        foreach (var sv in s.Vincoli)
            //        {
            //            if (v.Key == sv.Key)
            //            {
            //                dr[2] += " " + s.Id;
            //            }
            //        }
            //        foreach (var ps in s.Options)
            //        {
            //            string value = ps.Value;
                        
            //            int a = value.IndexOf("\"vincoli\":[\"")+12;
            //            if (a > 12)
            //            {
            //                int b = value.IndexOf("\"]", a) - a;
            //                value = value.Substring(a);
            //            }
            //            else value = "";
                        
                        
            //            if (value.Contains(v.Key))
            //            {
            //                dr[3] += " " + s.Id +"."  +ps.Key;
            //            }
            //        }
            //    }
                
            //    dt.Rows.Add(dr);
            //}

            GridView1.DataSource = dt;
            GridView1.DataBind();
            
        }

        protected void butLog_Click(object sender, EventArgs e)
        {
             string sqlconn ="";
             switch(((Button)sender).Text){
                 case   "LOGCOLLAUDO":
                         sqlconn = "Data Source=bfdspuc01c.fideuram.bancafideuram.it; Database=WebTemplateReportModeler;User Id=userHP; Password=userHP1; Max Pool Size=10";
                    break;
                 case   "LOGPREPRO":
                        sqlconn = "Data Source=bfdspuc01.fideuram.bancafideuram.it; Database=WebTemplateReportModeler;User Id=userHP; Password=userHP; Max Pool Size=10";
                    break;
                 case "LOGTEST":
                        sqlconn = "Data Source=bfdspuc01t.fideuram.bancafideuram.it; Database=WebTemplateReportModeler;User Id=userHP; Password=userHP1; Max Pool Size=10";
                    break;
                 default:
                         sqlconn = "Data Source=bfdspuc01c.fideuram.bancafideuram.it,53820; Database=WebTemplateReportModeler;User Id=userHP; Password=userHP; Max Pool Size=10";
                         break;
             }





            SqlCommand cmd = new SqlCommand("GETLOG", new SqlConnection(sqlconn));
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn{});
            dt.Columns.Add(new DataColumn {});
            dt.Columns.Add(new DataColumn {});
            dt.Columns.Add(new DataColumn {});
            while (rdr.Read())
                {
                    dt.Rows.Add(rdr[0], rdr[1], rdr[2], rdr[3]);
                }
            GridView1.DataSource = dt;
            GridView1.DataBind();
            foreach (GridViewRow r in GridView1.Rows) {
                for (int c = 0; c < 4; c++)
                {
                    r.Cells[c].ToolTip = System.Net.WebUtility.HtmlDecode(r.Cells[c].Text); 
                    if (r.Cells[c].Text.Length > 200)
                        r.Cells[c].Text = r.Cells[c].Text.Substring(0,200);
                }
            }
            //    r.Cells[1].ToolTip = r.Cells[1].Text;
            //    if (r.Cells[1].Text.Length > 100)
            //        r.Cells[1].Text =  r.Cells[1].Text.Substring(100);
            //    r.Cells[2].ToolTip = r.Cells[2].Text;
            //    if (r.Cells[2].Text.Length > 100)
            //        r.Cells[2].Text = r.Cells[2].Text.Substring(100);
            //}
           
           

           
        }

       

       

       

        











       


    }
}