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

public partial class archivioModelli : System.Web.UI.Page
{
    private DataTable dtDg;            
    private static bool b_sortCommand = true;

    public string codiceFiscale;      
    public int tpReport;                      //e' la tipologia corrente di Report. Puo' variare a seconda del valore selezionato dalla ListBox
    public string codiceRete;
    public string codicePB;
    public string pathNav;
    private string utente;
    public string recordsCancellati;
    public string recordsDaCancellare;
    public static int tpReportLauncher;      //memorizza tale valore per il tasto INDIETRO.
    public string caller;                    //tiene traccia se la pagina e' stata chiamata dalla spalla o da un determinato REPORT (diagnosi, proposta...etc.)
    public int idReportToLoadBack;           //memorizza con qualr report ID sono stato chiamato (per il tasto INDIETRO)
    public string nomeInizialeReport;
    public string descrizioneInizialeReport;
    public string checkPrivacy;
    public string token;

    //------------------------------------------------------------------------------------------
    protected void Page_Load(object sender, System.EventArgs e)
    {

        token = Request.QueryString.Get("token");         
        codiceFiscale = Request.QueryString.Get("codCliente");            
        codiceRete = Request.QueryString.Get("tipoRete");
        codicePB = Request.QueryString.Get("codPB");
        pathNav = Request.QueryString.Get("pathNav");
        tpReport = Convert.ToInt32(Request.QueryString.Get("tpReport"));
        utente = Request.QueryString.Get("tipoRete") + Request.QueryString.Get("codPB");
        recordsCancellati  = Request.QueryString.Get("deleted");
        recordsDaCancellare = Request.QueryString.Get("toBeDeleted");
        caller = Request.QueryString.Get("caller");
        idReportToLoadBack = Convert.ToInt32(Request.QueryString.Get("idReport"));
        nomeInizialeReport = Request.QueryString.Get("nomeInizialeReport");
        descrizioneInizialeReport = Request.QueryString.Get("descrizioneInizialeReport");
        checkPrivacy = Request.QueryString.Get("checkPrivacy");

        HttpCookie ck_idReportToLoadBack = new HttpCookie("reportToLoadBack");
        ck_idReportToLoadBack.Value = idReportToLoadBack.ToString();
        Response.Cookies.Add(ck_idReportToLoadBack);


        ////lettura del valore UTENTE dal cookie
        //HttpCookie ck_Utente = System.Web.HttpContext.Current.Request.Cookies["_utente"];
        //if (ck_Utente != null)
        //{
        //    utente = ck_Utente.Value.ToString();
        //}

        ck_idReportToLoadBack = new HttpCookie("reportToLoadBack");
        ck_idReportToLoadBack = System.Web.HttpContext.Current.Request.Cookies["reportToLoadBack"];
        if (ck_idReportToLoadBack != null)
        {
            idReportToLoadBack = Convert.ToInt32(ck_idReportToLoadBack.Value);
        }

        HttpCookie ck_codiceFiscale = new HttpCookie("codiceFiscale");
        ck_codiceFiscale = System.Web.HttpContext.Current.Request.Cookies["codiceFiscale"];
        if (ck_codiceFiscale != null)
        {
            codiceFiscale = ck_codiceFiscale.Value.ToString();
        }

        if (caller != null && caller != "0")     //il bottone INDIETRO deve comparire solo se la chiamata NON e' dalla spalla sinistra
        {
            this.btn_Indietro.Visible = true;
        }

        switch (Request.QueryString.Get("operation"))
        {
            case "RECORDDELETED":
                this.lbl_Message.Text = "Cancellati " + recordsCancellati + " modelli sui " + recordsDaCancellare + " da cancellare.";
                if(caller != null) this.btn_Indietro.Visible = true;
                break;
        }

        if (!Page.IsPostBack)
        {
            bool AccessoNoSessioneAutorizzato = false;
            if (Request.QueryString.Get("CODPB") != null && !Request.QueryString.Get("CODPB").Trim().Equals("") &&
                      Request.QueryString.Get("TIPORETE") != null && !Request.QueryString.Get("TIPORETE").Trim().Equals("") &&
                      (Request.QueryString.Get("CODCLIENTE") == null || Request.QueryString.Get("CODCLIENTE").Trim().Equals(""))
                    )
            { AccessoNoSessioneAutorizzato = true; }

            if (AccessoNoSessioneAutorizzato) 
            {

                this.ddl_Modello.SelectedValue = "8";
                this.ddl_Modello.Enabled = false;
                this.btn_CreaNuovo.Enabled = false;
                fillDG();
            }
            else
            {
                tpReportLauncher = tpReport;

                if (tpReport == 5) // d.lisena mi adeguo al codice scritto.
                    tpReport = 4;
                if (tpReport == 7)// a.nobili mi adeguo a d.lisena che si adegua al codice scritto.
                    tpReport = 5;
                this.ddl_Modello.SelectedIndex = tpReport - 1;
                fillDG();
            }
            
        }
                                          
    }
    //------------------------------------------------------------------------------------------
    private void dg_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
    {
        fillDG();
        DataView dv = new DataView(dtDg);
        if (b_sortCommand)
        {
            dv.Sort = e.SortExpression + " DESC";
            b_sortCommand = false;
        }
        else
        {
            dv.Sort = e.SortExpression + " ASC";
            b_sortCommand = true;
        }
        dg.DataSource = dv;
        dg.DataBind();
        try { foreach (DataGridItem item in dg.Items) ((Button)item.Cells[7].Controls[0]).Enabled = false; }
        catch { }   
    }
    //------------------------------------------------------------------------------------------
    public void dg_PageIndex(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
    {
        fillDG();
        dg.CurrentPageIndex = e.NewPageIndex;
        dg.DataSource = dtDg;
        dg.DataBind();
    }
    //------------------------------------------------------------------------------------------
    protected void fillDG()
    {
            this.lbl_Message.Text = "";
            
            tpReport = Convert.ToInt16(this.ddl_Modello.SelectedValue);

            if (tpReport == 7) {

                GestReport m = new GestReport();
                //int IdCliente = int.Parse(utente.Substring(1));
                string codiceRete = utente.Substring(0, 1);
                DataTable dt = m.AcquisisciTemplate(codicePB, codiceRete, codiceRete.Equals("F") ? 1 : 2);
                dtDg = new DataTable();
                dtDg.Columns.Add("nome");
                dtDg.Columns.Add("IdReport");
                dtDg.Columns.Add("DescrizioneModello");
                dtDg.Columns.Add("Descrizione");
                dtDg.Columns.Add("DtCreazione");
                dtDg.Columns.Add("TpReport");

                foreach (DataRow dr in dt.Rows)
                {

                    if (dr["DEFAULT"].ToString().Equals("S")) continue;

                    DataRow drins = dtDg.NewRow();
                    drins["nome"] = dr["nomeTemplate"];
                    drins["IdReport"] = dr["IdTemplate"];
                    drins["DescrizioneModello"] = "Rischio";
                    drins["Descrizione"] = dr["DEFAULT"].ToString().Equals("S") ? "Default" : "";
                    drins["DtCreazione"] = dr["DtCreazione"];
                    drins["TpReport"] = "7";
                    dtDg.Rows.Add(drins);

                }
                dg.DataSource = dtDg;
                dg.DataBind();
                dg.Visible = true;
                btn_CreaNuovo.Enabled = true;
            }
            else if (tpReport == 8) {
                GestReport m = new GestReport();               
                string codiceRete = utente.Substring(0, 1);
                DataTable dt = m.AcquisisciTemplate(codicePB, codiceRete, codiceRete.Equals("F") ? 3 : 4);
                dtDg = new DataTable();
                dtDg.Columns.Add("nome");
                dtDg.Columns.Add("IdReport");
                dtDg.Columns.Add("DescrizioneModello");
                dtDg.Columns.Add("Descrizione");
                dtDg.Columns.Add("DtCreazione");
                dtDg.Columns.Add("TpReport");

                foreach (DataRow dr in dt.Rows)
                {

                    if (dr["DEFAULT"].ToString().Equals("S")) continue;

                    DataRow drins = dtDg.NewRow();
                    drins["nome"] = dr["nomeTemplate"];
                    drins["IdReport"] = dr["IdTemplate"];
                    drins["DescrizioneModello"] = "Nucleo";
                    drins["Descrizione"] = dr["DEFAULT"].ToString().Equals("S") ? "Default" : "";
                    drins["DtCreazione"] = dr["DtCreazione"];
                    drins["TpReport"] = "7";
                    dtDg.Rows.Add(drins);

                }
                dg.DataSource = dtDg;
                dg.DataBind();
                dg.Visible = true;
                btn_CreaNuovo.Enabled = false;
                try { foreach (DataGridItem item in dg.Items) ((Button)item.Cells[7].Controls[0]).Enabled = false; }catch { }                
                    
            }
            else
            {
                List<Parametro> parametri = new List<Parametro>();
                Parametro parametro = new Parametro();
                parametro.DbType = DbType.Int32;
                parametro.Value = tpReport;
                parametro.ParameterName = "tpReport";
                parametri.Add(parametro);

                parametro = new Parametro();
                parametro.DbType = DbType.String;
                parametro.Value = utente;
                parametro.ParameterName = "utente";
                parametri.Add(parametro);
                dtDg = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServer, "sp_getReport_ByUtenteAndTipoReport", parametri);
                dg.DataSource = dtDg;
                dg.DataBind();
                dg.Visible = true;
                btn_CreaNuovo.Enabled = true;
            }
        
        
        
        
            
        //if (tpReport != 7)
        //    {
                
        //    }
        //    else {
                

        //        //for(int r=0;r<dt.Rows.Count;r++){
        //        //    if (dt.Rows[r]["DEFAULT"].ToString().Equals("S"))
        //        //    {
        //        //        ((CheckBox)dg.Items[r].FindControl("chk")).Enabled = false;
        //        //        ((CheckBox)dg.Items[r].FindControl("chk")).Checked = false;
        //        //    }
        //        //}
               
        //    } 
            
                   
           
            this.lbl_Message.ForeColor = System.Drawing.Color.Black;
            this.lbl_Message.Text = "Sono stati trovati " + dtDg.Rows.Count + " modelli attraverso il criterio di selezione prescelto.";

}

    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
        //
        // CODEGEN: This call is required by the ASP.NET Web Form Designer.
        //
        InitializeComponent();
        base.OnInit(e);
    }

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.dg.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.dg_PageIndex);
        this.dg.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dg_SortCommand);
        this.dg.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dg_ItemDataBound);

    }
    #endregion
    //------------------------------------------------------------------------------------------
    private void dg_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
    {
        //if (e.Item.ItemType != ListItemType.Header && e.Item.ItemType != ListItemType.Footer)
        //{
        //    Button deleteButton = (Button)e.Item.Cells[7].Controls[0];
        //    deleteButton.Attributes["onclick"] = "javascript:return " +
        //                "confirm('Siete sicuri di voler cancellare QUESTO modello?')";
        //}
    }
    //------------------------------------------------------------------------------------------
    protected void dg_Edit(object source, DataGridCommandEventArgs e)
    {
        string idReportToEdit = e.Item.Cells[1].Text.ToString();
        nomeInizialeReport = e.Item.Cells[2].Text.ToString();
        descrizioneInizialeReport = e.Item.Cells[4].Text.ToString();
        token = Request.QueryString["token"].ToString();
        tpReport = Convert.ToInt32(e.Item.Cells[6].Text);

        switch (tpReport) //tipologia report "con cui sono stato invocato"
        {
            case 1:      //DIAGNOSI
                Response.Redirect("reportDiagnosi.aspx?codCliente=" + codiceFiscale + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&idReportToLoad=" + idReportToEdit + "&nomeInizialeReport=" + nomeInizialeReport + "&descrizioneInizialeReport=" + descrizioneInizialeReport + "&checkPrivacy=" + checkPrivacy + "&token=" + token);
                break;
            case 2:      //PIANIFICAZIONE
                Response.Redirect("reportPianificazione.aspx?codCliente=" + codiceFiscale + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&idReportToLoad=" + idReportToEdit + "&nomeInizialeReport=" + nomeInizialeReport + "&descrizioneInizialeReport=" + descrizioneInizialeReport + "&checkPrivacy=" + checkPrivacy + "&token=" + token);
                break;
            case 3:      //PROPOSTA
                Response.Redirect("reportProposta_NEW.aspx?codCliente=" + codiceFiscale + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&idReportToLoad=" + idReportToEdit + "&nomeInizialeReport=" + nomeInizialeReport + "&descrizioneInizialeReport=" + descrizioneInizialeReport + "&checkPrivacy=" + checkPrivacy + "&token=" + token);
                break;
            case 4:      //MONITORAGGIO
            case 5:      //MONITORAGGIO
                Response.Redirect("reportMonitoraggio_Alberatura.aspx?codCliente=" + codiceFiscale + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&idReportToLoad=" + idReportToEdit + "&nomeInizialeReport=" + nomeInizialeReport + "&descrizioneInizialeReport=" + descrizioneInizialeReport + "&checkPrivacy=" + checkPrivacy + "&token=" + token);
                break;
            case 7:      //RISCHIO
                Session["HFNomeTemplate"] = e.Item.Cells[2].Text;
                Response.Redirect("reportRischioNew.aspx?codCliente=" + codiceFiscale + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&idReportToLoad=" + idReportToEdit + "&nomeInizialeReport=" + nomeInizialeReport + "&descrizioneInizialeReport=" + descrizioneInizialeReport + "&checkPrivacy=" + checkPrivacy + "&token=" + token);
                break;
            default:
                break;
        }
    }

   //------------------------------------------------------------------------------------------
    protected bool checkIfAtLeastOneItemClicked()
    {
        bool rc = false;
        for (int i = 0; i < dg.Items.Count; i++)
        {
            if (((CheckBox)dg.Items[i].FindControl("chk")).Checked == true)
            {
                rc = true;
                break;
            }
        }
        return rc;
    }
    //------------------------------------------------------------------------------------------
    protected void ddl_Modello_SelectedIndexChanged(object sender, EventArgs e)
    {
            tpReport = Convert.ToInt32(ddl_Modello.SelectedValue);
            fillDG();

    }
    //=====================================================================
    protected void btn_EliminaSelezionati_Click(object sender, EventArgs e)
    {
        this.lbl_Message.Text = "";
        bool rc = checkIfAtLeastOneItemClicked();

        if (rc)//almeno 1 item deputato alla cancellazione....
        {
            int reportToDelete;
            int deleted = 0;
            int itemsToDelete = 0;

            //conto il numero dei modelli da cancellare
            for (int i = 0; i < dg.Items.Count; i++)
            {
                if (((CheckBox)dg.Items[i].FindControl("chk")).Checked == true && ((CheckBox)dg.Items[i].FindControl("chk")).Visible == true)
                {
                    itemsToDelete++;
                }
            }

            for (int i = 0; i < dg.Items.Count; i++)
            {
                if (((CheckBox)dg.Items[i].FindControl("chk")).Checked == true)
                {
                    tpReport = Convert.ToInt32(ddl_Modello.SelectedValue);
                    int retCode = 0;
                    if (tpReport != 7 && tpReport != 8)
                    {
                        reportToDelete = Convert.ToInt32(dg.Items[i].Cells[1].Text);  //campo nascosto con l'ID del Report da cancellare
                        retCode = deleteReportFromDB(reportToDelete);
                    }
                    else {
                        retCode = deleteTemplateFromDB(int.Parse(dg.Items[i].Cells[1].Text));
                    
                    }
                    if (retCode != -1)
                    {
                        deleted++;
                    }
                }
            }
            if (deleted == itemsToDelete)
            {
                lbl_Message.ForeColor = System.Drawing.Color.Black;
            }
            
            Response.Redirect("archivioModelli.aspx?codCliente=" + codiceFiscale + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&pathNav=" + pathNav + "&tpReport=" + tpReport + "&utente=" + utente + "&deleted=" + deleted + "&toBeDeleted=" + itemsToDelete + "&operation=RECORDDELETED" + "&caller=" + caller + "&checkPrivacy=" + checkPrivacy + "&token=" + token);
            
        }
        else
        {
            //this.lbl_Message.ForeColor = System.Drawing.Color.Red;
            //this.lbl_Message.Text = "Attenzione. Selezionare almeno 1 MODELLO da cancellare.";
        }
    }
    //=====================================================================
    private int deleteReportFromDB(int reportToDelete)
    {
        int rc = 0;
        List<Parametro> parametri = new List<Parametro>();
        Parametro parametro = new Parametro();
        parametro.DbType = DbType.Int32;
        parametro.Value = reportToDelete;
        parametro.ParameterName = "idReport";
        parametri.Add(parametro);
        DataAccess.ExecuteNonQueryStoredProcedure(DBProvider.SqlServer, "sp_deleteReportFromDB_ByIdReport", parametri);
        return rc;
    }
    private int deleteTemplateFromDB(int idTemplate)
    {
        int rc = 0;
        try
        {
            GestReport m = new GestReport();
            m.CancellaTemplate(idTemplate);
        }
        catch {
            rc = -1;
        }
        return rc;
    }
    //=====================================================================
    protected void btn_CreaNuovo_Click(object sender, EventArgs e)
    {
        //torna alla pagina di gestione reportistica specifica caricando il MODELLO BASE x QUELLA TIPOLOGIA DI REPORT

        if (tpReport == 0)
        {
            tpReport = Convert.ToInt16(this.ddl_Modello.SelectedValue);
        }

        switch (tpReport)  //tipologia report "corrente"
        {
            case 1:      //DIAGNOSI
                Response.Redirect("reportDiagnosi.aspx?codCliente=" + codiceFiscale + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&idReportToLoad=loadBASE" + "&nomeInizialeReport=" + nomeInizialeReport + "&descrizioneInizialeReport=" + descrizioneInizialeReport + "&checkPrivacy=" + checkPrivacy + "&token=" + token);
                break;
            case 2:      //PIANIFICAZIONE
                Response.Redirect("reportPianificazione.aspx?codCliente=" + codiceFiscale + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&idReportToLoad=loadBASE" + "&nomeInizialeReport=" + nomeInizialeReport + "&descrizioneInizialeReport=" + descrizioneInizialeReport + "&checkPrivacy=" + checkPrivacy + "&token=" + token);
                break;
            case 3:      //PROPOSTA
                Response.Redirect("reportProposta_new.aspx?codCliente=" + codiceFiscale + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&idReportToLoad=loadBASE" + "&nomeInizialeReport=" + nomeInizialeReport + "&descrizioneInizialeReport=" + descrizioneInizialeReport + "&checkPrivacy=" + checkPrivacy + "&token=" + token);
                break;
            case 4:      //MONITORAGGIO
            case 5:      //MONITORAGGIO

                Response.Redirect("reportMonitoraggio_Alberatura.aspx?codCliente=" + codiceFiscale + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&idReportToLoad=loadBASE" + "&nomeInizialeReport=" + nomeInizialeReport + "&descrizioneInizialeReport=" + descrizioneInizialeReport + "&checkPrivacy=" + checkPrivacy + "&token=" + token);
                break;
            case 7:      //RISCHIO
                Response.Redirect("reportRischioNew.aspx?codCliente=" + codiceFiscale + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&idReportToLoad=loadBASE" + "&nomeInizialeReport=" + nomeInizialeReport + "&descrizioneInizialeReport=" + descrizioneInizialeReport + "&checkPrivacy=" + checkPrivacy + "&token=" + token);
                break;
          
            default:
                break;
        }

    }
    //=====================================================================
    protected void btn_Indietro_Click(object sender, EventArgs e)
    {
        switch (tpReport) //tipologia report "con cui sono stato invocato"
        {
            case 1:      //DIAGNOSI
                Response.Redirect("reportDiagnosi.aspx?codCliente=" + codiceFiscale + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&idReportToLoad=" + idReportToLoadBack + "&nomeInizialeReport=" + nomeInizialeReport + "&descrizioneInizialeReport=" + descrizioneInizialeReport + "&checkPrivacy=" + checkPrivacy + "&token=" + token);
                break;
            case 2:      //PIANIFICAZIONE
                Response.Redirect("reportPianificazione.aspx?codCliente=" + codiceFiscale + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&idReportToLoad=" + idReportToLoadBack + "&nomeInizialeReport=" + nomeInizialeReport + "&descrizioneInizialeReport=" + descrizioneInizialeReport + "&checkPrivacy=" + checkPrivacy + "&token=" + token);
                break;
            case 3:      //PROPOSTA
                Response.Redirect("reportProposta_new.aspx?codCliente=" + codiceFiscale + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&checkPrivacy=" + checkPrivacy + "&token=" + token);
                break;
            case 4:      //MONITORAGGIO
            case 5:      //MONITORAGGIO
                Response.Redirect("reportMonitoraggio_Alberatura.aspx?codCliente=" + codiceFiscale + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&idReportToLoad=" + idReportToLoadBack + "&nomeInizialeReport=" + nomeInizialeReport + "&descrizioneInizialeReport=" + descrizioneInizialeReport + "&checkPrivacy=" + checkPrivacy + "&token=" + token);
                break;
            case 7:      //RISCHIO
                Session["HFNomeTemplate"] = null;
                Response.Redirect("reportRischioNew.aspx?codCliente=" + codiceFiscale + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&idReportToLoad=" + idReportToLoadBack + "&nomeInizialeReport=" + nomeInizialeReport + "&descrizioneInizialeReport=" + descrizioneInizialeReport + "&checkPrivacy=" + checkPrivacy + "&token=" + token);
                break;
            default:
                break;
        }
    }
    //=====================================================================
}