using DevExpress.Web;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrintingLinks;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OlympiaIntranet
{
    public partial class VerificheAML : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated == false)
            {
                Response.Redirect("~/SignIn.aspx");
            }
            
            if (IsPostBack) // Rielabora il grafico altrimenti il print non la stampa.
            {
                CaricaDatiGriglie();
            }
        }

        private void CaricaDatiGriglie()
        {
            ASPxGridView grid = gridLookupConsulente.GridView;
            object objConsulente = grid.GetRowValues(grid.FocusedRowIndex, new string[] { "Consulente" });
            // if (!(objGestore != null && objLinea != null && objConsulente != null)) return;
            if (objConsulente == null)
            {
                CommonClass.MessageBox(this, "Selezionare Consulente!");
                return;
            }
            if (String.IsNullOrEmpty(cbTipoAttività.Text) == true)
            {
                CommonClass.MessageBox(this, "Selezionare Tipo Attività!");
                return;
            }
            if (String.IsNullOrEmpty(cbSocieta.Text) == true)
            {
                CommonClass.MessageBox(this, "Selezionare Tipo Società!");
                return;
            }
            if (deMeseRiferimento.Date == new DateTime(1,1,1))
            {
                CommonClass.MessageBox(this, "Selezionare Mese Riferimento!");
                return;
            }

            // Carica dati Guardian leggendoli dall'excel \Dropbox\Olympia\Relazioni.xls che viene caricato da Slavko prima di generare i report
            DataTable dtDatiGuardian = CommonClass.execQuery_Datatable_Sql("GDN_VerificheAML_Load", 
                                                                           Properties.Settings.Default.SqlConnection, 
                                                                           "", 
                                                                           (string)objConsulente, 
                                                                           "",
                                                                           -1,
                                                                           -1,
                                                                           null, 
                                                                           cbTipoAttività.Text, 
                                                                           cbSocieta.Text, 
                                                                           deMeseRiferimento.Date);
            gvDatiGuardian.DataSource = dtDatiGuardian;
            gvDatiGuardian.KeyFieldName = "KeyID";
            gvDatiGuardian.DataBind();

            DataTable dtReport = CommonClass.execQuery_Datatable_Sql("GDN_VerificheAML_Report",
                                                                           Properties.Settings.Default.SqlConnection,
                                                                           "",
                                                                           (string)objConsulente,
                                                                           "",
                                                                           -1,
                                                                           -1,
                                                                           null,
                                                                           cbTipoAttività.Text,
                                                                           cbSocieta.Text,
                                                                           deMeseRiferimento.Date);
            gvReport.DataSource = dtReport;
            gvReport.KeyFieldName = "KeyID";
            gvReport.DataBind();

        }

        protected void btnElaboraDati_Click(object sender, EventArgs e)
        {

        }

        protected void btnEsportaPdf_Click(object sender, EventArgs e)
        {
            //ASPxGridViewExporter1.ExportSelectedRowsOnly = false;
            //ASPxGridViewExporter1.FileName = DateTime.Now.ToString("yyyyMMdd_HHmm") + " - Report AML";
            //ASPxGridViewExporter1.ReportHeader = $"Report per AML - Mese: {deMeseRiferimento.Text} \r\nConsulente: {gridLookupConsulente.Text} Tipo Attività: {cbTipoAttività.Text} Società: {cbSocieta.Text}";
            //ASPxGridViewExporter1.WritePdfToResponse();

            using (MemoryStream ms = new MemoryStream())
            {
                /*
                PrintableComponentLinkBase pcl = new PrintableComponentLinkBase(new PrintingSystemBase());
                pcl.Component = ASPxGridViewExporter1;
                pcl.Margins.Left = pcl.Margins.Right = 50;
                pcl.Landscape = true;
                pcl.CreateDocument(false);
                pcl.PrintingSystemBase.Document.AutoFitToPagesWidth = 1;
                pcl.ExportToPdf(ms);
                WriteResponse(this.Response, ms.ToArray(), System.Net.Mime.DispositionTypeNames.Inline.ToString());
                */

                // Esportare gridview in landscape con header di testo
                // ref: https://github.com/DevExpress-Examples/how-to-display-content-in-the-header-and-footer-sections-when-exporting-aspxgridview-e3184
                PrintingSystemBase ps = new PrintingSystemBase();
                PrintableComponentLinkBase pcl = new PrintableComponentLinkBase(new PrintingSystemBase());
                pcl.Component = ASPxGridViewExporter1;
                pcl.PrintingSystemBase.Document.AutoFitToPagesWidth = 1;
                CompositeLinkBase compositeLink = new CompositeLinkBase(ps);
                LinkBase header = new LinkBase();
                header.CreateDetailHeaderArea += Header_CreateDetailHeaderArea;
                compositeLink.Landscape = true;
                compositeLink.Links.AddRange(new object[] { header, pcl });
                compositeLink.CreateDocument();
                compositeLink.ExportToPdf(ms);
                WriteToResponse(DateTime.Now.ToString("yyyyMMdd_HHmm") + " - Report AML", true, "pdf", ms);
            }
        }
        void Header_CreateDetailHeaderArea(object sender, CreateAreaEventArgs e)
        {
            e.Graph.BorderWidth = 0;
            Rectangle r = new Rectangle(0, 0, 500, 50);
            e.Graph.DrawString($"Report per AML - Mese: {deMeseRiferimento.Text} \r\nConsulente: {gridLookupConsulente.Text} Tipo Attività: {cbTipoAttività.Text} Società: {cbSocieta.Text}",r);
        }
        void WriteToResponse(string fileName, bool saveAsFile, string fileFormat, MemoryStream stream)
        {
            if (Page == null || Page.Response == null) return;
            string disposition = saveAsFile ? "attachment" : "inline";
            Page.Response.Clear();
            Page.Response.Buffer = false;
            Page.Response.AppendHeader("Content-Type", string.Format("application/{0}", fileFormat));
            Page.Response.AppendHeader("Content-Transfer-Encoding", "binary");
            Page.Response.AppendHeader("Content-Disposition",
                string.Format("{0}; filename={1}.{2}", disposition, fileName, fileFormat));
            Page.Response.BinaryWrite(stream.ToArray());
            Page.Response.End();
        }

        public static void WriteResponse(HttpResponse response, byte[] filearray, string type)
        {
            response.ClearContent();
            response.Buffer = true;
            response.Cache.SetCacheability(HttpCacheability.Private);
            response.ContentType = "application/pdf";
            ContentDisposition contentDisposition = new ContentDisposition();
            contentDisposition.FileName = DateTime.Now.ToString("yyyyMMdd_HHmm") + " - Report AML";
            contentDisposition.DispositionType = type;
            response.AddHeader("Content-Disposition", contentDisposition.ToString());
            response.BinaryWrite(filearray);
            HttpContext.Current.ApplicationInstance.CompleteRequest();
            try
            {
                response.End();
            }
            catch (System.Threading.ThreadAbortException)
            {
            }

        }
    }
}