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 archivioDocumentiNucleo : 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)
    {
      

        
            dPage = new RequestNucleo(Request);

            if (!Page.IsPostBack)
            {
                if (!GetUtenteAutorizzato.getAccessoPortaleAutorizzato())
                {
                    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;
                        }
                    }

                }
                if (!GetUtenteAutorizzato.getAccessoPortaleAutorizzato())
                    fillDG("", 0);
                else 
                    fillDG2("", 0);
            }
         
    }

    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 imageRichiedi_Click(object sender, EventArgs e)
    {

        VediRichiedi((LinkButton)sender);
    }
    protected void btn_ButLog_Click(object sender, EventArgs e)
    {
        VediDocumenit();
    }
    protected void btn_ButNote_Click(object sender, EventArgs e)
    {
        VediDocumenit();
    }
    protected void btn_ButRichiediNo_Click(object sender, EventArgs e)
    {
        VediDocumenit();
    }
    protected void btn_ButRichiediSi_Click(object sender, EventArgs e)
    {
        RichiediDocumento();
        
        ButRichiediSi.Enabled = false;
    }
    
    //=====================================================================

    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;
        tbRichiedi.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;
        tbRichiedi.Visible = false;
        tbNote.Visible = true;
    }
    private void VediRichiedi(LinkButton button)
    {
        lbl_MessageRichiesta.Text = "";
        lbl_MessageRichiesta.ForeColor = System.Drawing.Color.Black;

        //string txt = "Ha richiesto il Report di [tipo] del Cliente [Nominativo], generato in data [dtCreazione].";
        string txt = "Ha richiesto il Report NUCLEO " + button.Attributes["nomeNucleo"] + ", generato in data "; 
        
        if (button.Attributes["dtCreazione"].ToString().Length >= 10)
           txt += button.Attributes["dtCreazione"].Substring(0, 10);
        if (button.Attributes["dtCreazione"].ToString().Length > 10)
            txt += button.Attributes["dtCreazione"].Substring(10);   
        txt+= ".";

        ButRichiediSi.Attributes.Add("idPdf", button.Attributes["idPdf"]);
        ButRichiediSi.Enabled= true;
        ButRichiediNo.Enabled = true;
        
        tbRichiedi.Visible = true;
        tbDocumenti.Visible = false;
        tbLog.Visible = false;
        tbNote.Visible = false;

        txRichiedi.Text = txt;

    }
    private void VediDocumenit()
    {
        tbDocumenti.Visible = true;
        tbLog.Visible = false;
        tbNote.Visible = false;
        tbRichiedi.Visible = false;
    }
    private void RichiediDocumento()
    {
       
        int ris = 0;
        try
        {
            ris = daoNuclei.RichiediDocumento(long.Parse(ButRichiediSi.Attributes["idPdf"]));
            for (int i = 0; i < dg.Items.Count; i++)
            {
                LinkButton anchorRichiedi = ((LinkButton)dg.Items[i].FindControl("anchorRichiedi"));
                if (anchorRichiedi.Attributes["IdPdf"] != null && anchorRichiedi.Attributes["IdPdf"].Equals(ButRichiediSi.Attributes["idPdf"]))
                {
                     anchorRichiedi.Visible = false;
                    ((HtmlImage)dg.Items[i].FindControl("imageRichiedi")).Visible = false;
                    ((HtmlAnchor)dg.Items[i].FindControl("anchorPdf")).Visible = true;
                    ((HtmlImage)dg.Items[i].FindControl("imagePdf")).Visible = true;
                  
                } 
            }
            
        }
        catch { ris = 0; }           
             
        if (ris == 1)
        {

            lbl_MessageRichiesta.Text = "La richiesta � stata inoltrata con successo";
           
        }
        else
        {     lbl_MessageRichiesta.ForeColor = System.Drawing.Color.Red;
              lbl_MessageRichiesta.Text = "La richiesta non � stata inoltrata a causa di un problema tecnico; contattare l'Help Desk";    
        }
    }
    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 void fillDG2(string sort, int currentPageIndex)
    {
        try
        {
            VediDocumenit();
             
            DataTable dtDg = new DataTable("Table");
            dtDg.Columns.Add("idPdf");
            dtDg.Columns.Add("dtCreazione");	
            dtDg.Columns.Add("idProvenienza");	
            dtDg.Columns.Add("TpReport");
            dtDg.Columns.Add("idStato");	
            dtDg.Columns.Add("idArchivio");	
            dtDg.Columns.Add("dtRestore");	
            dtDg.Columns.Add("CodicePB");	
            dtDg.Columns.Add("Rete");	
            dtDg.Columns.Add("NumeroPagine");	
            dtDg.Columns.Add("Note");	
            dtDg.Columns.Add("dtEliminato");	
            dtDg.Columns.Add("chiaveNucleo");
            dtDg.Columns.Add("NomeNucleo");

            dg.CurrentPageIndex = currentPageIndex;
            dg.DataSource = dtDg;
            dg.DataBind();
            this.lbl_Message.ForeColor = System.Drawing.Color.Black;
            this.lbl_Message.Text = "";  
        }
        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")) {
            chk.Attributes.Add("IdPdf", drv["IdPdf"].ToString());
            chk.Visible = true;            
        } else {
            chk.Visible = false;    
        }

        HtmlImage imageStato = ((HtmlImage)item.FindControl("imageStato"));
        imageStato.Src = "Images/icon-Richiesta_scalata.jpg";
        if (!drv["idArchivio"].Equals("O") && !drv["idArchivio"].Equals("R"))
        {           
            imageStato.Visible = true;
        }
        else {
            imageStato.Visible = false;
        }


       

        



        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"));
        LinkButton anchorRichiedi = ((LinkButton)item.FindControl("anchorRichiedi"));
        HtmlImage imageRichiedi = ((HtmlImage)item.FindControl("imageRichiedi"));
        anchorRichiedi.Visible = false;
        imageRichiedi.Visible = false;

        switch(drv["idArchivio"].ToString()){           
            case "A": // Archiviato
                 anchorRichiedi.Visible = true;
                 imageRichiedi.Visible = true;
                 anchorRichiedi.ToolTip = "Clicca per richiedere il documento";
                 imageRichiedi.Src = "Images/richiediDoc.jpg";
                 anchorRichiedi.Attributes.Add("dtCreazione", drv["dtCreazione"].ToString());
                 anchorRichiedi.Attributes.Add("nomeNucleo", drv["nomeNucleo"].ToString());
                 anchorRichiedi.Attributes.Add("idPdf", drv["idPdf"].ToString());   
                 anchorPdf.Visible = false;
                 imagePdf.Visible = false;
                 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 "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 (Debug.iSDebug)
        {
            anchorLog.ToolTip = "IdPdf = " + drv["idpdf"].ToString() +
                                " ChiaveNucleo = " + drv["ChiaveNucleo"].ToString() +
                                " Archivio = " + drv["idarchivio"].ToString() +
                                " Stato = " + drv["idstato"].ToString() +
                                " Dtrestore = " + drv["dtrestore"].ToString() +
                                " Tpreport(8) = " + drv["tpreport"].ToString();
            


        }
      //ISIMAGE	gg	gg2	idPdf	dtCreazione	idProvenienza	TpReport	idStato	idArchivio	dtRestore	CodicePB	Rete	NumeroPagine	Note
 

       
    }

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

    
 










     
}