using DevExpress.Web;
using DevExpress.XtraCharts;
using DevExpress.XtraCharts.Native;
using DevExpress.XtraCharts.Web;
using DevExpress.Pdf;
using DevExpress.XtraPrinting;
using DevExpress.XtraGrid;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OlympiaIntranet
{

    public partial class GPMAssetAllocation : System.Web.UI.Page
    {
        string[] adminUser = new string[] { "fcostalonga", "ecanziani", "fpisoni", "glicciardello" };
        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated == false)
            {
                Response.Redirect("~/SignIn.aspx");
            }
            else
            {
                string loggedUser = HttpContext.Current.User.Identity.Name;

                if (adminUser.Contains(loggedUser) == true) { gridLookupGestore.Enabled = true; }
                else
                {
                    gridLookupGestore.Value = loggedUser.Substring(1).ToUpper();
                    gridLookupGestore.Enabled = false;
                }

                Session["cod_ges"] = gridLookupGestore.Value; // serve per popolare gridlookupLinea!!
                //Session["cod_adv"] = gridLookupAdvisor.Value; // serve per popolare gridlookupLinea!!
                Session["user"] = loggedUser; // serve per popolare gridlookupGestore!!
            }

            if (IsPostBack) // Rielabora il grafico altrimenti il print non la stampa.
            {
                PlottaFullStackedBar();
            }
        }

        protected void buttonGeneraGrafici_Click(object sender, EventArgs e)
        {
            PlottaFullStackedBar();
        }

        private void PlottaFullStackedBar()
        {
            // Carica dati in dtStackedBarsData 
            ASPxGridView grid = gridLookupGestore.GridView;
            object objGestore = grid.GetRowValues(grid.FocusedRowIndex, new string[] { "Gestore" });
            grid = gridLookupLinea.GridView;
            object objLinea = grid.GetRowValues(grid.FocusedRowIndex, new string[] { "Linea" });

            //grid = gridLookupAdvisor.GridView;
            //object objAdvisor = grid.GetRowValues(grid.FocusedRowIndex, new string[] { "Advisor" });
            //if (!(objGestore != null && objLinea != null && objAdvisor != null)) return;

            if (!(objGestore != null && objLinea != null)) return;
            DataTable dtStackedBarsData = CommonClass.execQuery_Datatable_Sql("GDN_GPMAssetAllocation_StackedBars2",
                                                                              Properties.Settings.Default.SqlConnection,
                                                                              (string)objGestore,
                                                                              "",
                                                                              (string)objLinea,
                                                                              -1,
                                                                              -1,
                                                                              null,
                                                                              "",
                                                                              "",
                                                                              null,
                                                                              ""
                                                                              );
            Session["dtStackedBarsData"] = dtStackedBarsData;
            var listAssetClass = (from r in dtStackedBarsData.AsEnumerable()
                                  group r by r["Asset Class"]);

            /*
            WebChartControl fullStackedBarChart = new WebChartControl
            {
                DataSource = dtStackedBarsData,
                RenderFormat = RenderFormat.Svg,
                Height = 768,
                Width = 1024,
                EnableViewState = false, // necessario altrimenti non riaggiorna il grafico!
                AppearanceName = "Gray"
            };
            */

            fullStackedBarChart.DataSource = dtStackedBarsData;

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

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

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

            // Setta titolo del grafico
            SettaTitoloGrafico(fullStackedBarChart);


            foreach (var groupedAssetClass in listAssetClass)
            {
                string AssetClass = (string)groupedAssetClass.Key;
                Series series = new Series(AssetClass, ViewType.FullStackedBar);
                foreach (var seriesPoint in groupedAssetClass)
                {
                    series.Points.Add(new SeriesPoint(seriesPoint["Codice Portafoglio"], seriesPoint["Esposizione"]));
                }
                series.ArgumentScaleType = ScaleType.Qualitative;
                series.CrosshairContentShowMode = CrosshairContentShowMode.Default;
                series.CrosshairLabelPattern = "{S}: {V:F2}%"; // ref link : https://docs.devexpress.com/CoreLibraries/DevExpress.XtraCharts.SeriesBase.CrosshairLabelPattern

                FullStackedBarSeriesView seriesView = (FullStackedBarSeriesView)series.View;
                switch (AssetClass)
                {
                    case "Fondi Bilanciati e Flessibili":
                        seriesView.Color = Color.LightCyan;
                        break;
                    case "Liquidità":
                        seriesView.Color = Color.LightGreen;
                        break;
                    case "Obbligazioni e Fondi Obbligazionari":
                        seriesView.Color = Color.LightSalmon;
                        break;
                    case "Prodotti Strutturati":
                        seriesView.Color = Color.MediumPurple;
                        break;
                    case "Azioni e Fondi Azionari":
                        seriesView.Color = Color.OrangeRed;
                        break;
                    case "Real Estate":
                        seriesView.Color = Color.Orange;
                        break;
                    default:
                        break;
                }
                seriesView.BarWidth = 0.4;
                fullStackedBarChart.Series.Add(series);
            }

            // Posiziona la legenda sopra e fuori dal grafico 
            // ref link: https://docs.devexpress.com/CoreLibraries/DevExpress.XtraCharts.LegendBase.AlignmentHorizontal
            Legend legend = fullStackedBarChart.Legend;
            legend.AlignmentHorizontal = LegendAlignmentHorizontal.Center;
            legend.AlignmentVertical = LegendAlignmentVertical.TopOutside;
            legend.MaxHorizontalPercentage = 100;
            legend.Direction = LegendDirection.LeftToRight;

            // Hide the legend (if necessary).
            fullStackedBarChart.Legend.Visibility = DevExpress.Utils.DefaultBoolean.True;
            fullStackedBarChart.CrosshairOptions.GroupHeaderPattern = "Portafoglio: {A}";

            // Add the chart to the form.
            //this.Controls.Add(fullStackedBarChart);

            // Ruota etichetta sulle ascisse di 180
            XYDiagram diagram = (XYDiagram)fullStackedBarChart.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}";

                // Aggiunge legenda relativa ai ptf in basso              
                Legend ptfLegend = new Legend();
                fullStackedBarChart.Legends.Add(ptfLegend);

                ptfLegend.DockTarget = diagram.Panes.GetPaneByName("Default");
                ptfLegend.AlignmentHorizontal = LegendAlignmentHorizontal.Center;
                ptfLegend.AlignmentVertical = LegendAlignmentVertical.BottomOutside;
                ptfLegend.ItemVisibilityMode = LegendItemVisibilityMode.AutoGeneratedAndCustom;
                ptfLegend.MarkerMode = LegendMarkerMode.None;
                ptfLegend.MaxHorizontalPercentage = 100;
                ptfLegend.Direction = LegendDirection.LeftToRight;

                AggiungeItemLegend(ptfLegend, "(A) = ATTIVO");
                AggiungeItemLegend(ptfLegend, "(AR) = ATTIVO-RIC");
                AggiungeItemLegend(ptfLegend, "(V) = VIRTUALE");
                //AggiungeItemLegend(ptfLegend, "(P) = PENDING");
                //AggiungeItemLegend(ptfLegend, "(C) = IN CHIUSURA");
            }

            fullStackedBarChart.DataBind();
        }

        private void AggiungeItemLegend(Legend ptfLegend, string legendText)
        {
            CustomLegendItem item = new CustomLegendItem
            {
                Text = legendText
            };
            ptfLegend.CustomItems.Add(item);
        }

        private string TitoloFiltri()
        {
            string filtro = String.Empty;
            if (String.IsNullOrEmpty(gridLookupGestore.Text) == true) { filtro += "Gestore: tutti "; } else { filtro += $"Gestore: {gridLookupGestore.Text} "; }
            //if (String.IsNullOrEmpty(gridLookupAdvisor.Text) == true) { filtro += "Advisor: tutti "; } else { filtro += $"Advisor: {gridLookupAdvisor.Text} "; }
            if (String.IsNullOrEmpty(gridLookupLinea.Text) == true) { filtro += "Linea: tutti "; } else { filtro += $"Linea: {gridLookupLinea.Text} "; }
            return (filtro);
        }

        private void SettaTitoloGrafico(WebChartControl chartControl)
        {
            // Create chart titles.
            ChartTitle chartTitle1 = new ChartTitle();
            ChartTitle chartTitle2 = new ChartTitle();
            // Define the text for the titles.
            chartTitle1.Text = "<b>GPM ASSET ALLOCATION</b>";

            chartTitle2.Text = TitoloFiltri();

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

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

            // 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.Bold);
            chartTitle2.TextColor = Color.Black;
            chartTitle2.Indent = 10;

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

        protected void buttonEsportaPdf_Click(object sender, EventArgs e)
        {

            // Esporta grafico in pdf 
            //var ps = new PrintingSystem();
            //ps.PageSettings.Landscape = true;
            //var link1 = new PrintableComponentLink();
            //fullStackedBarChart.DataBind();
            //link1.Component = ((IChartContainer)fullStackedBarChart).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=GPMAssetAllocation_{DateTime.Now.Date.ToString("yyyyMMdd")}.pdf");
            //    Response.BinaryWrite(stream.GetBuffer());
            //    Response.End();
            //}
            //ps.Dispose();

        }

        protected void gridLookupGestore_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 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 verrà effettuato nell'evento lato client EndCallBack

            ASPxGridView grid = gridLookupGestore.GridView;
            object objGestore = grid.GetRowValues(grid.FocusedRowIndex, new string[] { "Gestore" });

            if (objGestore != null)
            {
                Session["cod_ges"] = (string)objGestore;
            }

        }

        //protected void gridLookupAdvisor_ValueChanged(object sender, EventArgs e)
        //{
        //    ASPxGridView grid = gridLookupAdvisor.GridView;
        //    object objAdvisor = grid.GetRowValues(grid.FocusedRowIndex, new string[] { "Advisor" });

        //    if (objAdvisor != null)
        //    {
        //        Session["cod_adv"] = (string)objAdvisor;
        //    }
        //}
    }
}