using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.CodeParser;
using DevExpress.Web;
using DevExpress.XtraCharts;
using DevExpress.XtraCharts.Native;
using DevExpress.XtraCharts.Web;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrintingLinks;

namespace OlympiaIntranet
{
    public partial class MonitorVaR : System.Web.UI.Page
    {       

        protected void Page_Load(object sender, EventArgs e)
        {
            // Se è la prima volta che viene caricata la pagina allora carica glGestore e cancella tutto quello che c'è in glLinea
            if (IsPostBack == false)
            {
                BindGestori();
                glLinea.DataSource = null;
                glLinea.DataBind();
            }

        }

        private void BindGestori()
        {
            using (SqlConnection conn = new SqlConnection(OlympiaIntranet.Properties.Settings.Default.SqlConnection))
            using (SqlCommand cmd = new SqlCommand("GDN_GetGestore", conn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                conn.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(dr);
                glGestore.DataSource = dt;
                glGestore.DataBind();
            }
        }

        private void PlottaGrafico(DataTable dataTable)
        {
            // Cancella tutte le serie prima di plottare 
            chartControl.Series.Clear();

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

            // Setta titolo del grafico
            SettaTitoloGrafico();

            // Setta posizione legenda
            Legend legend = chartControl.Legend;
            legend.AlignmentHorizontal = LegendAlignmentHorizontal.Center;
            legend.AlignmentVertical = LegendAlignmentVertical.BottomOutside;
            legend.Direction = LegendDirection.LeftToRight;

            // Create a new bar series.
            Series series = new Series("# pos. sconfinanti per VaR puntuale", ViewType.Line);
            series.ArgumentScaleType = ScaleType.DateTime;
            series.ArgumentDataMember = "Data";
            series.ValueScaleType = ScaleType.Numerical;
            series.ValueDataMembers.AddRange(new string[] { "NumDeltaPuntuale" });
            chartControl.Series.Add(series);

            Series series1 = new Series("# pos. sconfinanti per VaR medio", ViewType.Line);
            series1.ArgumentScaleType = ScaleType.DateTime;
            series1.ArgumentDataMember = "Data";
            series1.ValueScaleType = ScaleType.Numerical;
            series1.ValueDataMembers.AddRange(new string[] { "NumDeltaMedio" });
            chartControl.Series.Add(series1);

            // Specify the series data source.
            series.DataSource = dataTable;
            series1.DataSource = dataTable;

            XYDiagramSeriesViewBase view = (XYDiagramSeriesViewBase)series.View;
            LineSeriesView ssv = view as LineSeriesView;
            ssv.MarkerVisibility = DevExpress.Utils.DefaultBoolean.False;

            XYDiagramSeriesViewBase view1 = (XYDiagramSeriesViewBase)series1.View;
            LineSeriesView ssv1 = view1 as LineSeriesView;
            ssv1.MarkerVisibility = DevExpress.Utils.DefaultBoolean.False;
        }

        private void SettaTitoloGrafico()
        {
            // Create chart titles.
            ChartTitle chartTitle1 = new ChartTitle();
            ChartTitle chartTitle2 = new ChartTitle();
            // Define the text for the titles.
            chartTitle1.Text = "<b>Numero posizioni sconfinanti per VaR</b>";
            
            chartTitle2.Text = TitoloFiltri();

            chartTitle2.WordWrap = true;
            chartTitle2.MaxLineCount = 2;

            // Define the alignment of the titles.
            chartTitle1.Alignment = StringAlignment.Near;
            chartTitle2.Alignment = StringAlignment.Near;

            // Place the titles where it's required.
            chartTitle1.Dock = ChartTitleDockStyle.Top;
            chartTitle2.Dock = ChartTitleDockStyle.Top;

            // Customize a title's appearance.
            chartTitle1.EnableAntialiasing = DevExpress.Utils.DefaultBoolean.True;
            chartTitle1.Font = new Font("Tahoma", 14, FontStyle.Bold);
            chartTitle1.TextColor = Color.Blue;
            chartTitle1.Indent = 10;

            // Customize a title's appearance.
            chartTitle2.EnableAntialiasing = DevExpress.Utils.DefaultBoolean.True;
            chartTitle2.Font = new Font("Arial", 10, FontStyle.Italic);
            chartTitle2.TextColor = Color.Black;
            chartTitle2.Indent = 10;

            // Add the titles to the chart.
            chartControl.Titles.AddRange(new ChartTitle[] {chartTitle1,chartTitle2});
        }

        private string TitoloFiltri()
        {
            string filtro = String.Empty;
            if (String.IsNullOrEmpty(glGestore.Text) == true) { filtro += "Gestore: tutti "; } else { filtro += $"Gestore: {glGestore.Text} "; }
            if (String.IsNullOrEmpty(glLinea.Text) == true) { filtro += "Linea: tutti "; } else { filtro += $"Linea: {glLinea.Text} "; }
            return (filtro);
        }

        protected void btnEsportaPdf_Click(object sender, EventArgs e)
        {
            /*
            // Esporta grafico in pdf 
            var ps = new PrintingSystem();
            ps.PageSettings.Landscape = true;
            var link1 = new PrintableComponentLink();
            chartControl.DataBind();
            link1.Component = ((IChartContainer)chartControl).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=HomePageCharts.pdf");
                Response.BinaryWrite(stream.GetBuffer());
                Response.End();
            }
            ps.Dispose();
            */

            if (!(String.IsNullOrEmpty(glGestore.Text) || String.IsNullOrEmpty(glLinea.Text)))
            {
                string query = CommonClass.ExecSql("monitorVaR_LoadData1", glGestore.Text, glLinea.Text);
                var dataTable = CommonClass.execQuery_Datatable_MySql(query, Properties.Settings.Default.mySqlConnection);

                // Plotta il grafico in server-side, così da assicurarti che sia pronto per l'esportazione
                PlottaGrafico(dataTable);

                var ps = new PrintingSystem();
                ps.PageSettings.Landscape = true;

                var link = new PrintableComponentLink(ps)
                {
                    Component = ((IChartContainer)chartControl).Chart,
                    Landscape = true
                };

                link.CreateDocument();
                ps.Document.AutoFitToPagesWidth = 1;

                using (var stream = new MemoryStream())
                {
                    ps.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=monitorVar_{DateTime.Now:yyyyMMdd_HHmmss}.pdf");
                    Response.BinaryWrite(stream.ToArray());
                    Response.End();
                }

                ps.Dispose();
            }
        }

        protected void glGestore_ValueChanged(object sender, EventArgs e)
        {
            // ref: https://supportcenter.devexpress.com/ticket/details/q340370/aspxgridlookup-how-to-refresh-the-control-after-some-data-is-changed
            // note: Per refreshare gridlookupLinea e gridlookupAdvisor sulla base del valore di gridLookupGestore, salvo il valore gestore in una variabile di sessione Session["cod_ges"] 
            //       e poi il refresh/rebind di SqlDSLinee e SqlDSAdvisor verrà effettuato nell'evento lato client EndCallBack

            if (glGestore.Value != null && String.IsNullOrEmpty(glGestore.Value.ToString()) == false)
            {
                BindLineeByGestore(glGestore.Text);
            }
            else
            {
                glLinea.DataSource = null;
                glLinea.DataBind();
            }
        }
        private void BindLineeByGestore(string Gestore)
        {
            using (SqlConnection conn = new SqlConnection(OlympiaIntranet.Properties.Settings.Default.SqlConnection))
            using (SqlCommand cmd = new SqlCommand("GDN_GetLinee1", conn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@cod_ges", Gestore);
                //cmd.Parameters.AddWithValue("@cod_adv", "-- TUTTI --");
                conn.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(dr);
                glLinea.DataSource = dt;
                glLinea.DataBind();
            }
        }



        protected void btnShowChart_Click(object sender, EventArgs e)
        {
                if (!(String.IsNullOrEmpty(glGestore.Text) == true || String.IsNullOrEmpty(glLinea.Text) == true))
                {
                    string query = CommonClass.ExecSql("monitorVaR_LoadData1", glGestore.Text, glLinea.Text);

                    var dataTable = CommonClass.execQuery_Datatable_MySql(query, Properties.Settings.Default.mySqlConnection); // DataIns, NumDeltaPuntuale, NumDeltaMedio

                    PlottaGrafico(dataTable);
                }
        }
    }
}