using DevExpress.XtraCharts;
using DevExpress.XtraCharts.Native;
using DevExpress.XtraPrinting;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OlympiaIntranet
{
    public partial class PerformanceYTDLineeAPI : System.Web.UI.Page
    {
        string tipo = String.Empty;

        protected void Page_Init(object sender, EventArgs e)
        {
            CultureInfo ci = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
            ci.NumberFormat.NumberDecimalSeparator = ",";
            Thread.CurrentThread.CurrentCulture = ci;
        }
        protected void Page_Load(object sender, EventArgs e) // Parametro input : tipo = "table" | "chart" 
        {
            tipo = Request.QueryString["tipo"];

            if (tipo == "chart")
            {
                PlottaBarChart();

                EsportaChart_pdf();
            }

            if (tipo == "table")
            {
                PopulateTable();

                EsportaTable_pdf();
            }
        }

        private void EsportaTable_pdf()
        {
            ASPxGridViewExporter1.ExportSelectedRowsOnly = false;
            ASPxGridViewExporter1.FileName = $"PerformanceYTD_Table_{ DateTime.Now.Date.ToString("yyyyMMdd")}.pdf"; // DateTime.Now.ToString("yyyyMMdd_HHmm") + " - Performance YTD Linee";
            PdfExportOptions op = new PdfExportOptions() { };
            ASPxGridViewExporter1.WritePdfToResponse(op);
        }

        private void PopulateTable()
        {
            DataTable dtBarsData = CommonClass.execQuery_Datatable_Sql("GDN_PerformanceYTDLinee_Load", Properties.Settings.Default.SqlConnection);
            Session["BarsData"] = dtBarsData;
            gvPerformanceYTDLinee.DataSource = dtBarsData;
            gvPerformanceYTDLinee.DataBind();
        }

        private void EsportaChart_pdf()
        {
            // Esporta grafico in pdf 
            var ps = new PrintingSystem();
            ps.PageSettings.Landscape = true;
            var link1 = new PrintableComponentLink();
            barChart.DataBind();
            link1.Component = ((IChartContainer)barChart).Chart;
            link1.Landscape = true;
            link1.PrintingSystem = ps;
            link1.CreateDocument();
            ps.Document.AutoFitToPagesWidth = 1; // Fit to page 

            using (var stream = new MemoryStream())
            {
                link1.PrintingSystem.ExportToPdf(stream);
                Response.Clear();
                Response.Buffer = false;
                Response.AppendHeader("Content-Type", "application/pdf");
                Response.AppendHeader("Content-Transfer-Encoding", "binary");
                Response.AppendHeader("Content-Disposition", $"attachment; filename=PerformanceYTD_Chart_{DateTime.Now.Date.ToString("yyyyMMdd")}.pdf");
                Response.BinaryWrite(stream.GetBuffer());
                Response.End();
            }
            ps.Dispose();
        }

        private void PlottaBarChart()
        {
            DataTable dtBarsData = CommonClass.execQuery_Datatable_Sql("GDN_PerformanceYTDLinee_Load", Properties.Settings.Default.SqlConnection);
            Session["BarsData"] = dtBarsData;
            gvPerformanceYTDLinee.DataSource = dtBarsData;
            gvPerformanceYTDLinee.DataBind();

            barChart.DataSource = dtBarsData;

            // Cancella tutte le serie prima di plottare 
            barChart.Series.Clear();

            // Cancella tutti i titoli della serie prima di plottare
            barChart.Titles.Clear();

            // Rimuove legenda aggiuntiva dei portafogli
            barChart.Legends.Clear();

            // Aggiunge barre al grafico relative a PerfYTDAvg
            Series series1 = new Series("Perf. YTD (Avg)", ViewType.Bar);
            foreach (DataRow rowBars in dtBarsData.Rows)
            {
                series1.Points.Add(new SeriesPoint(rowBars[0].ToString(), rowBars[1]));
            }
            barChart.Series.Add(series1);

            // Aggiunge barre al grafico relative a PerfYTDStd
            Series series2 = new Series("Perf. YTD (Std)", ViewType.Bar);
            foreach (DataRow rowBars in dtBarsData.Rows)
            {
                series2.Points.Add(new SeriesPoint(rowBars[0].ToString(), rowBars[2]));
            }
            barChart.Series.Add(series2);


            // Hide the legend (if necessary).
            barChart.Legend.Visibility = DevExpress.Utils.DefaultBoolean.False;

            // Ruota etichetta sulle ascisse di 180
            XYDiagram diagram = (XYDiagram)barChart.Diagram;
            if (diagram != null)
            {
                // Ruota etichetta sulle ascisse di 180
                diagram.AxisX.Label.Angle = -90;
                diagram.AxisX.QualitativeScaleOptions.AutoGrid = false; // ref link: https://supportcenter.devexpress.com/ticket/details/t567170/how-to-force-displaying-all-axis-labels-when-the-qualitative-scale-type-is-used
                diagram.AxisX.QualitativeScaleOptions.GridSpacing = 1;

                // Rimuove margini su asse Y
                diagram.AxisY.WholeRange.AutoSideMargins = false;
                diagram.AxisY.WholeRange.EndSideMargin = 0;
                diagram.AxisY.WholeRange.StartSideMargin = 0;

                // Setta Ordinate (Asse Y) in percentuale
                //diagram.AxisY.Label.TextPattern = "{VP:P0}";

            }

            // Add a title to the chart (if necessary).
            ChartTitle chartTitle1 = new ChartTitle();
            chartTitle1.Text = "Performance YTD (Avg) / Performance YTD (Std)";
            barChart.Titles.Add(chartTitle1);
        }
    }
}