using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


using System.Drawing;
using System.Collections.Generic;
using ceTe.DynamicPDF;
using ReportVS;
using ceTe.DynamicPDF.Merger;
using LogFilePDF;







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

    #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);
    }


    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

    public RequestNucleo dPage = null;
    public DaoNucleo daoNuclei = new DaoNucleo();
    //=====================================================================   
    
    protected void Page_Load(object sender, System.EventArgs e)
    {

        GestioneStampe gs = new GestioneStampe();
        gs.datiNavigazione.CaptionNav = "Archivio documenti Nucleo";

        if (GetUtenteAutorizzato.getAccessoPortaleAutorizzato())
        {
            dPage = new RequestNucleo();

            if (!IsPostBack)
            {
                txb_Rete.Enabled = false;
                txb_CodicePB.Enabled = false;
                txb_ClienteCF.Enabled = false;
                txb_ClienteCognome.Enabled = false;
                txb_ClienteNome.Enabled = false;
                txt_nomenucleo.Enabled = false;
                DatiHDUS datiHDUS = GetUtenteAutorizzato.getDatiHDUS();
                txb_Rete.Text = datiHDUS.Rete;
                txb_CodicePB.Text = datiHDUS.CodicePB;
                txb_ClienteCF.Text = datiHDUS.CodiceFiscale;
                txb_ClienteCognome.Text = datiHDUS.CognomeCliente;
                txb_ClienteNome.Text = datiHDUS.NomeCliente;
                btn_EliminaSelezionati.Visible = false;
            }
            string command = "SimpleContextMenu.setup({'preventDefault':true, 'preventForms':false});SimpleContextMenu.attach('container', 'CM1');";
            ClientScript.RegisterClientScriptBlock(typeof(string), "pppppp", "<script language=\"javascript\" type=\"text/javascript\">" + "\n" + "<!--" + "\n" + command + "\n" + "//-->" + "\n" + "</script>");

        }
        else
        {
            dPage = new RequestNucleo();
            dPage.codiceRete = gs.datiNavigazione.Rete;
            dPage.codicePB = gs.datiNavigazione.Agente;
            dPage.codCliente = gs.datiNavigazione.CfIva;

           

            if (!Page.IsPostBack)
            {
                txb_Rete.Enabled = false;
                txb_CodicePB.Enabled = false;
                txb_Rete.Text = dPage.codiceRete;
                txb_CodicePB.Text = dPage.codicePB;

                if (!dPage.codCliente.Equals(""))
                {
                    this.txb_ClienteCF.Text = dPage.cfIva;

                    if (!dPage.codMandato.Equals(""))
                    {
                        this.txb_ClienteCognome.Text = dPage.codMandato;
                    }
                    else
                    {
                        Cliente cliente = Cliente.getCliente(dPage.utente, dPage.codCliente);
                        if (cliente != null)
                        {
                            this.txb_ClienteCognome.Text = cliente.Cognome;
                            this.txb_ClienteNome.Text = cliente.Nome;
                        }
                    }

                }
                fillDG("", 0);
            }
        }

        //switch (Request.QueryString.Get("operation"))
        //{
        //    case "DOCUMENTDELETED":
        //        this.lbl_Message.Text = "Cancellati " + dPage.recordsCancellati + " documenti sui " + dPage.recordsDaCancellare + " da cancellare.";
        //        break;

        //    case "DOCUMENTARCHIVED":
        //        this.lbl_Message.Text = "Archiviati " + dPage.recordsArchiviati + " documenti sui " + dPage.recordsDaArchiviare + " da archiviare.";
        //        break;
        //}
    }

    private void dg_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
    {
        fillDG(e.SortExpression, 0);
    }

    public void dg_PageIndex(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
    {
        fillDG("", e.NewPageIndex);
    }

    protected void btn_Ricerca_Click(object sender, EventArgs e)
    {
        fillDG("CodicePB", 0);
    }

    protected void btn_Azzera_Click(object sender, EventArgs e)
    {
        if (GetUtenteAutorizzato.getAccessoPortaleAutorizzato())
        {
            this.txb_da.Text = "";
            this.txb_a.Text = "";
        }
        else
        {
            this.txt_nomenucleo.Text = "";
            this.txb_da.Text = "";
            this.txb_a.Text = "";
            this.txb_ClienteCognome.Text = "";
            this.txb_ClienteNome.Text = "";
            this.txb_ClienteCF.Text = "";
            this.cldSF_a.SelectedDate = new DateTime(1, 1, 1);
            this.cldSF_da.SelectedDate = new DateTime(1, 1, 1);
            this.chk_RicercaStampedaRichiedere.Checked = false;
        }
        this.lbl_Message.Text = "";
    }

    protected void imgCalendar_Da_Click(object sender, ImageClickEventArgs e)
    {
        if (!this.cldSF_da.Visible)
        {
            DateTime dt = DateTime.Now;
            try { dt = Convert.ToDateTime(this.txb_da.Text); }
            catch { }
            this.cldSF_da.SelectedDate = dt;
        }
        this.cldSF_da.Visible = !this.cldSF_da.Visible;
        if (this.cldSF_a.Visible) this.cldSF_a.Visible = false;
    }

    protected void imgCalendar_a_Click(object sender, ImageClickEventArgs e)
    {
        if (!this.cldSF_a.Visible)
        {
            DateTime dt = DateTime.Now;
            try { dt = Convert.ToDateTime(this.txb_a.Text); }
            catch { }
            this.cldSF_a.SelectedDate = dt;
        }
        this.cldSF_a.Visible = !this.cldSF_a.Visible;
        if (this.cldSF_da.Visible) this.cldSF_da.Visible = false;
    }

    protected void cldSF_da_SelectionChanged(object sender, EventArgs e)
    {
        this.txb_da.Text = this.cldSF_da.SelectedDate.ToShortDateString();
        this.cldSF_da.Visible = false;
    }

    protected void cldSF_a_SelectionChanged(object sender, EventArgs e)
    {
        this.txb_a.Text = this.cldSF_a.SelectedDate.ToShortDateString();
        this.cldSF_a.Visible = false;
    }

    private void dg_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            ItemDataBound((DataGridItem)e.Item);

    }

    protected void btn_EliminaSelezionati_Click(object sender, EventArgs e)
    {
        EliminaSelezionati();
    }
    protected void imageLog_Click(object sender, EventArgs e)
    {

        vedilog((LinkButton)sender);
    }
    protected void imageNote_Click(object sender, EventArgs e)
    {

        vediNote((LinkButton)sender);
    }

    protected void btn_ButLog_Click(object sender, EventArgs e)
    {
        VediDocumenit();
    }
    protected void btn_ButNote_Click(object sender, EventArgs e)
    {
        VediDocumenit();
    }
    
    //=====================================================================

    private void vedilog(LinkButton button)
    {
        DataTable dt = daoNuclei.RicercaLog(int.Parse(button.Attributes["IdPdf"]));
        dt.Columns.Add("utente");
        foreach (DataRow dr in dt.Rows) dr["utente"] = dPage.utente;
        dgLog.DataSource = dt;
        dgLog.DataBind();
        
        tbDocumenti.Visible = false;
        tbLog.Visible = true;
    }
    private void vediNote(LinkButton button)
    {

        LabelCliente.Text = button.Attributes["nomeNucleo"];
        LabelReport.Text = "NUCLEO";
        if (button.Attributes["dtCreazione"].ToString().Length >= 10)   
            lblData.Text = button.Attributes["dtCreazione"].Substring(0, 10);
        if (button.Attributes["dtCreazione"].ToString().Length > 10)  
            lblOra.Text = button.Attributes["dtCreazione"].Substring(10);        
        lbNote.Text = button.Attributes["note"];
        
        tbDocumenti.Visible = false;
        tbNote.Visible = true;
    }     
    private void VediDocumenit()
    {
        tbDocumenti.Visible = true;
        tbLog.Visible = false;
        tbNote.Visible = false;
    }

    private void EliminaSelezionati()
    {


        lbl_Message.ForeColor = System.Drawing.Color.Black;
        lbl_Message.Text = "";
        int tChecked = 0;
        int tDeleted = 0;

        try
        {
            for (int i = 0; i < dg.Items.Count; i++)
            {
                CheckBox chk = ((CheckBox)dg.Items[i].FindControl("chk"));
                if (chk.Checked)  {
                    tChecked++;
                    int ris = daoNuclei.EliminaPdfNuclei(Convert.ToInt32(chk.Attributes["IdPdf"]));
                    tDeleted += ris;
                    if (ris > 0)   {
                        chk.Checked = false;
                        dg.Items[i].Visible = false;
                    }
                }
            }
        }
        catch (Exception ex) { }

        if (tChecked == 0)
        {
            this.lbl_Message.Text = "Attenzione. Selezionare almeno un DOCUMENTO da cancellare.";
        }
        else
        {
            this.lbl_Message.Text = "Cancellati " + tDeleted + " documenti sui " + tChecked + " da cancellare.";
            if (tDeleted != tChecked) lbl_Message.ForeColor = System.Drawing.Color.Red;
        }

    }
    private void fillDG(string sort, int currentPageIndex)
    {
        try
        {
            VediDocumenit();
            setTypedData();
            if (checkTypedData().Equals(""))
            {
                DataTable dtDg = GetData(sort);
                dg.CurrentPageIndex = currentPageIndex;
                dg.DataSource = dtDg;
                dg.DataBind();


                this.lbl_Message.ForeColor = System.Drawing.Color.Black;
                this.lbl_Message.Text = "Sono stati trovati " + dtDg.Rows.Count + " documenti con il criterio di ricerca prescelto.";
            }
            else
            {
                this.lbl_Message.ForeColor = System.Drawing.Color.Red;
                this.lbl_Message.Text = checkTypedData();
            }


        }
        catch (Exception ex)
        {
            this.lbl_Message.ForeColor = System.Drawing.Color.Red;
            this.lbl_Message.Text = "Errore nella ricerca documenti";
        }

    }
    private string SortDG(string column)
    {

        if (dg.Attributes["column"] == null)
        {
            dg.Attributes.Add("column", column);
            dg.Attributes.Add("order", "ASC");
        }
        else if (dg.Attributes["column"].Equals(column))
        {
            dg.Attributes["order"] = dg.Attributes["order"].Equals("ASC") ? "DESC" : "ASC";
        }
        else
        {
            dg.Attributes["column"] = column;
            dg.Attributes["order"] = "ASC";
        }

        return dg.Attributes["column"] + " " + dg.Attributes["order"];
    }
    private void setTypedData()
    {
        dPage.cmpRic.rete = txb_Rete.Text;
        dPage.cmpRic.codicePb = txb_CodicePB.Text;
        dPage.cmpRic.cfiva = txb_ClienteCF.Text;
        dPage.cmpRic.cognome = txb_ClienteCognome.Text;
        dPage.cmpRic.nome = txb_ClienteNome.Text;
        dPage.cmpRic.nomeNucleo = txt_nomenucleo.Text;
        dPage.cmpRic.dt_da = txb_da.Text;
        dPage.cmpRic.dt_a = txb_a.Text;
        dPage.cmpRic.Archivio = chk_RicercaStampedaRichiedere.Checked;
    }
    private string checkTypedData()
    {
        Validation vld = new Validation();

        if ((dPage.cmpRic.cfiva.Length == 11 && !vld.IsNaturalNumber(dPage.cmpRic.cfiva)) ||
            (dPage.cmpRic.cfiva.Length == 16 && !vld.IsValidCF(dPage.cmpRic.cfiva)) ||
            (dPage.cmpRic.cfiva.Length != 0 && dPage.cmpRic.cfiva.Length != 16 && dPage.cmpRic.cfiva.Length != 11))
            return "Attenzione. Codice Fiscale NON valido.";

        if (!dPage.cmpRic.dt_da.Equals("") && !vld.IsData(dPage.cmpRic.dt_da))
            return "Attenzione. Data di inizio periodo NON valida.";

        if (!dPage.cmpRic.dt_a.Equals("") && !vld.IsData(dPage.cmpRic.dt_a))
            return "Attenzione. Data di fine periodo NON valida.";

        if ((!dPage.cmpRic.dt_da.Equals("") && !dPage.cmpRic.dt_a.Equals("")) &&
            (Convert.ToDateTime(this.txb_a.Text) < Convert.ToDateTime(this.txb_da.Text)))
            return "Attenzione. Data di fine periodo inferiore alla data di inizio periodo.";

        return "";
    }
    private DataTable GetData(string sort)
    {
        DataTable dt = daoNuclei.RicercaPdfNuclei(dPage.cmpRic);
        if (!sort.Equals(""))
        {
            DataView dv = new DataView(dt);
            dv.Sort = SortDG(sort);
            dt = dv.ToTable("Table");
        }
        return dt;
    }

    private void ItemDataBound(DataGridItem item)
    {
        DataRowView drv = (DataRowView)item.DataItem;
        dg.Attributes.Add("IdPdf", drv["IdPdf"].ToString());

        CheckBox chk = ((CheckBox)item.FindControl("chk"));
        if (!drv["idArchivio"].Equals("O"))
        {
            HtmlImage imageStato = ((HtmlImage)item.FindControl("imageStato"));
            imageStato.Src = "Images/icon-Richiesta_scalata.jpg";
            imageStato.Visible = true; 
          
            chk.Visible = false;            
        }
        else {
            chk.Visible = true;
            chk.Attributes.Add("IdPdf", drv["IdPdf"].ToString());
        }

        



        if (!drv["note"].Equals(""))
        {
            LinkButton anchorNote = ((LinkButton)item.FindControl("anchorNote"));
            anchorNote.ToolTip = "Click per vedere le note";
            anchorNote.Visible = true;
            anchorNote.Attributes.Add("dtCreazione",drv["dtCreazione"].ToString());
            anchorNote.Attributes.Add("note", drv["note"].ToString());
            anchorNote.Attributes.Add("nomeNucleo", drv["nomeNucleo"].ToString());            
        }
             

        LinkButton anchorLog = ((LinkButton)item.FindControl("anchorLog"));
        anchorLog.Attributes.Add("IdPdf", drv["IdPdf"].ToString());
        anchorLog.ToolTip = "Click per vedere il log";


        HtmlAnchor anchorPdf = ((HtmlAnchor)item.FindControl("anchorPdf"));
        HtmlImage imagePdf = ((HtmlImage)item.FindControl("imagePdf"));
       

        switch(drv["idArchivio"].ToString()){           
            case "A": // Archiviato
                 anchorPdf.Title = "Clicca per richiedere il documento";
                 anchorPdf.HRef ="";// "richiediDocumentinuclei.aspx";// "richiediDocumenti.aspx?Nominativo="; 
                 imagePdf.Src = "Images/richiediDoc.jpg";
                break;
            case "C": // RichiestaRestore
                anchorPdf.Title = "Recupero documento in corso";
                anchorPdf.HRef = "";
                imagePdf.Src = "Images/richiediDoc_disabilitata.jpg";                
                imagePdf.Attributes.Add("onmouseover", "this.style.cursor='wait';");
                imagePdf.Attributes.Add("onmouseout", "this.style.cursor='default';");
                break;
            case "R": // Restorato
            case "O": // Online
                anchorPdf.Title = "Clicca per vedere il documento";
                anchorPdf.HRef = "javascript:showPdf(" + drv["IdPdf"].ToString() + ")";
                imagePdf.Src = "Images/PDF-Icon.jpg";
                break;
                 
        }
        


      

        if (GetUtenteAutorizzato.getAccessoPortaleAutorizzato())
        {
            item.Attributes.Add("oncontextmenu", "javascript:ShowContextMenu(" + item.ItemIndex + "," + drv["Identificativo"] + ",1,'" + txb_Rete.Text.Trim() + "','" + txb_ClienteCF.Text.Trim() + "');");
        }
    }

    //=====================================================================

    
 










     
}