using System;
using System.Collections.Generic;
using System.Linq;
using Consulenza.ExternalServices;
using Consulenza.ReportWriter.Business;
using Consulenza.ReportWriter.Business.OBJ_PDF;
using System.Data;
using Consulenza.ReportWriter.Business.CHART_PDF;
using Consulenza.ReportCommon;
using Consulenza.ReportWriter.Business.Entity;
using System.Text;
using System.Drawing;
using Dundas.Charting.WebControl;
using System.Globalization;
using System.IO;
using System.Drawing.Imaging;

namespace Consulenza.ReportWriter.Manager.Section.Immobiliare.Monitoraggio
{
    /// <summary>
    /// Scheda 14
    /// </summary>
    public class S14 : Entity.Section
    {
        public bool bFlag = false;

        public S14(EnvironmentFacade environmentFacade, int idSection)
            : base(environmentFacade, idSection)
        {
            try
            {
                if (idSection == 999)
                    bFlag = true;
                else
                    bFlag = false;

                Draw();
            }
            catch (Exception ex)
            {
                SectionLogger.Write("S14", ex.Message, SectionLoggerMessageLevel.E, EnvironmentFacade.ReportEnvironment);
            }
        }

        /// <summary>
        /// Scheda2. Patrimonio immobiliare –Sintesi (distribuzione del patrimonio complessivo del cliente diviso per tipologia e cointestatari)
        /// </summary>
        protected override void Draw()
        {
            var data = GetDataSet();
            var image = getImageFromStored();
            AddElement(new FormattedTextAreaPDF("Di seguito si rappresenta la distribuzione geografica degli immobili nei comuni di appartenenza per numerosità e valore stimato.", 30)
            {
                AutoIncrementYWritable = false,
                Width = 800,
                FontSize = 9.96f,
                FontColor = new ColorPDF(91, 88, 79),
                Y = 60
            });

            Single nScale = 0;
            if (bFlag == true)
            {
                //nScale = 0.245f;
                nScale = 0.37f;
            }
            else
            {
                nScale = 0.37f;
            }

            AddElement(new ImagePDF(20, nScale, image)//new Prometeia().GetImageMonitoraggioFromValidator(EnvironmentFacade.ReportEnvironment.Cliente.CodiceFiscale))
            {
                AutoIncrementYWritable = false,
                Y = 87
            });

            AddElement(new FormattedTextAreaPDF("Numerosità immobili – distribuzione per Comune", 350)
            {
                AutoIncrementYWritable = false,
                Width = 800,
                FontSize = 9,
                FontColor = new ColorPDF(91, 88, 79),
                Y = 85,
                FontBold = true
            });

            AddElement(new FormattedTextAreaPDF("Valore stimato totale (€) – distribuzione per Comune", 350)
            {
                AutoIncrementYWritable = false,
                Width = 800,
                FontSize = 9,
                FontColor = new ColorPDF(91, 88, 79),
                Y = 260,
                FontBold = true
            });

            var chart1Records = GetChartData(data, 4);
            DrawChart1(chart1Records);
            var chart2Records = GetChartData(data, 1);
            DrawChart2(chart2Records);
            AddElement(new ResetterYPDF());
            DrawLegend(350, 437);
            AddElement(new PagePDF(PagePDF.PagePDFType.Generic));
            AddElement(new FormattedTextAreaPDF("Di seguito si rappresenta il valore stimato degli immobili distribuiti per tipologia comune e posizione urbana.", 30)
            {
                AutoIncrementYWritable = false,
                Width = 800,
                FontSize = 9.96f,
                FontColor = new ColorPDF(91, 88, 79),
                Y = 60
            });
            AddElement(new ImagePDF(20, nScale, image)//new Prometeia().GetImageMonitoraggioFromValidator(EnvironmentFacade.ReportEnvironment.Cliente.CodiceFiscale))
            {
                AutoIncrementYWritable = false,
                Y = 87
            });

            AddElement(new FormattedTextAreaPDF("Valore stimato totale (€) – distribuzione per tipologia Comune", 350)
            {
                AutoIncrementYWritable = false,
                Width = 800,
                FontSize = 9,
                FontColor = new ColorPDF(91, 88, 79),
                Y = 85,
                FontBold = true
            });

            AddElement(new FormattedTextAreaPDF("Valore stimato totale (€) – distribuzione per posizione urbana", 350)
            {
                AutoIncrementYWritable = false,
                Width = 800,
                FontSize = 9,
                FontColor = new ColorPDF(91, 88, 79),
                Y = 260,
                FontBold = true
            });

            var chart3Records = GetChartData(data, 3);
            DrawChart3(chart3Records);

            var chart4Records = GetChartData(data, 2);
            DrawChart4(chart4Records);
            DrawLegend(350, 444);

        }

        /// <summary>
        /// Recupera i dati necessari alla Section restituendo un DataTable.
        /// </summary>
        /// <returns></returns>
        protected override DataTable GetDataTable()
        {
            return null;
        }

        /// <summary>
        /// Recupera i dati necessari alla Section restituendo un DataSet.
        /// </summary>
        /// <returns></returns>
        protected override DataSet GetDataSet()
        {
            var parametri = new List<Parametro>
            {
                new Parametro
                {
                    Direction = ParameterDirection.Input,
                    DbType = DbType.Int32,
                    ParameterName = "chiaveClientePB",
                    Value = EnvironmentFacade.ReportEnvironment.Cliente.Chiave
                }
            };

            //return DataAccess.ExecuteDataSetStoredProcedure(DBProvider.SqlServerConsulenzaUnica, "REP_ImmobiliareMonitoraggio_S14_MapDistrGeografica_NEW", parametri);
            return DataAccess.ExecuteDataSetStoredProcedure(DBProvider.SqlServerConsulenzaUnica, "REP_ImmobiliareMonitoraggio_S14_MapDistrGeografica", parametri);
            
        }

        private List<ChartRecord> GetChartData(DataSet dataSet, int chiaveTipoChart)
        {
            List<ChartRecord> results = new List<ChartRecord>();
            foreach (DataRow row in dataSet.Tables[0].Rows)
            {
                if ((int)row["chiaveTipoChart"] == chiaveTipoChart)
                {
                    ChartRecord chartRecord = new ChartRecord()
                    {
                        ChiaveTipoChart = (int)row["chiaveTipoChart"],
                        KeyMappature = (string)row["keyMappatura"],
                        ValUsoAbitativo = (decimal)(row["valUsoAbitativo"] != DBNull.Value ? (decimal)row["valUsoAbitativo"] : 0),
                        ValUsoStrumentale = (decimal)(row["valUsoStrumentale"] != DBNull.Value ? (decimal)row["valUsoStrumentale"] : 0),
                        ValUsoInvestimento = (decimal)(row["valUsoInvestimento"] != DBNull.Value ? (decimal)row["valUsoInvestimento"] : 0),
                        ValUsoNS = (decimal)(row["valUsoNS"] != DBNull.Value ? (decimal)row["valUsoNS"] : 0),
                        ValTotaleTipologia = (decimal)(row["valTotaleTipologia"] != DBNull.Value ? (decimal)row["valTotaleTipologia"] : 0),
                        NumImmobili = (decimal)row["numImmobili"],
                        OrderInGraph = (string)row["OrderInGraph"]
                    };

                    chartRecord.UsoTipologia = chartRecord.ValUsoAbitativo > 0 ? "Immobili d'uso abitativo" :
                                                chartRecord.ValUsoStrumentale > 0 ? "Immobili strumentali" :
                                                chartRecord.ValUsoInvestimento > 0 ? "Immobili d'investimento" :
                                                chartRecord.ValUsoNS > 0 ? "Finalità non specificata" : "Finalità non specificata";
                    if (!string.IsNullOrEmpty(chartRecord.UsoTipologia))
                    {
                        results.Add(chartRecord);
                    }
                }
            }
            return results;
        }

        private Color[] ChartsColors = new Color[]
        {
            Color.FromArgb(206, 219, 209),
            Color.FromArgb(167, 192, 168),
            Color.FromArgb(114, 152, 110),
            Color.FromArgb(245, 245, 220)
        };

        private void DrawChart1(List<ChartRecord> chartRecords)
        {
            List<ChartRecord> chartRec;
            chartRec = chartRecords.OrderByDescending(x => x.NumImmobili).ToList();

            //chartRecords = chartRecords.OrderByDescending(x => x.NumImmobili).ToList();
            chartRecords = chartRecords.OrderBy(x => x.OrderInGraph).ThenByDescending(x => x.NumImmobili).ToList();

            if (chartRecords.Count > 4)
            {
                decimal valUsoAbitativo = 0;
                decimal valUsoStrumentale = 0;
                decimal valUsoInvestimento = 0;
                decimal valUsoNS = 0;

                for (int i = 4; i < chartRecords.Count; i++)
                {
                    valUsoAbitativo += chartRecords[i].ValUsoAbitativo;
                    valUsoStrumentale += chartRecords[i].ValUsoStrumentale;
                    valUsoInvestimento += chartRecords[i].ValUsoInvestimento;
                    valUsoNS += chartRecords[i].ValUsoNS;
                }
                
                // Commento ES per problemi con Categoria Altro 10/08/2017
                //chartRecords.RemoveRange(4, chartRecords.Count - 4);
                //chartRecords.Add(new ChartRecord()
                //{
                //    ValUsoAbitativo = valUsoAbitativo,
                //    ValUsoInvestimento = valUsoInvestimento,
                //    ValUsoNS = valUsoNS,
                //    ValUsoStrumentale = valUsoStrumentale,
                //    KeyMappature = "Altro",
                //    NumImmobili = valUsoAbitativo + valUsoInvestimento + valUsoNS + valUsoStrumentale
                //});
            }


            //AddElement(new SpacePDF(50));
            //int nLeftStart;
            //if (chartRec[0].NumImmobili > 9)
            //    nLeftStart = 378;
            //else
            //    nLeftStart = 386;

            int nLeftStart;
            int nWidth = 339;
            switch ((int)chartRec[0].NumImmobili)
            {
                case 1:
                case 2:
                    nLeftStart = 368;
                    nWidth = 357;
                    break;
                
                case 3:
                case 4:
                case 5:
                case 6:
                case 7:
                case 8:
                case 9:
                    nLeftStart = 386;
                    break;
                default:
                    nLeftStart = 378;
                    nWidth = 347;
                    break;
            }

            var customChart = new CustomChartPDF()
            {
                X = nLeftStart,
                Y = 115
            };

            var baseChart = customChart.ChartBase;
            baseChart.Width = new System.Web.UI.WebControls.Unit(nWidth);
            baseChart.Height = new System.Web.UI.WebControls.Unit(136);
            baseChart.ChartAreas.Add("Default");
            baseChart.ChartAreas["Default"].Area3DStyle.Enable3D = false;
            baseChart.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
            baseChart.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
            baseChart.ChartAreas[0].AxisX.LabelsAutoFit = true;
            baseChart.ChartAreas[0].AxisX.LabelsAutoFitStyle = LabelsAutoFitStyle.WordWrap;
            baseChart.ChartAreas[0].AxisY.LabelStyle.Font = new Font("Verdana", 6);
            baseChart.ChartAreas[0].AxisX.LabelStyle.Font = new Font("Verdana", 5);
            baseChart.ChartAreas[0].AxisX.MajorTickMark.Enabled = false;
            baseChart.ChartAreas[0].AxisX.MinorTickMark.Enabled = false;
            baseChart.Legends[0].Docking = LegendDocking.Bottom;
            baseChart.Legends[0].Alignment = StringAlignment.Center;
            baseChart.Legends[0].Font = new Font("Verdana", 6);
            baseChart.Legends[0].Enabled = false;
                        
            var valUsoAbitativoRecords =
                chartRecords.Where(x => x.ValUsoAbitativo > 0).Select(x => new
                {
                    KeyMappature = x.KeyMappature,
                    UsoTipologia = "Immobili d'uso abitativo",
                    ValUsoTotal = x.ValUsoAbitativo
                }).ToList();

            var ValUsoStrumentaleRecords =
            chartRecords.Where(x => x.ValUsoStrumentale > 0).Select(x => new
            {
                KeyMappature = x.KeyMappature,
                UsoTipologia = "Immobili strumentali",
                ValUsoTotal = x.ValUsoStrumentale
            }).ToList();

            var ValUsoInvestimentoRecords =
            chartRecords.Where(x => x.ValUsoInvestimento > 0).Select(x => new
            {
                KeyMappature = x.KeyMappature,
                UsoTipologia = "Immobili d'investimento",
                ValUsoTotal = x.ValUsoInvestimento
            }).ToList();


            var ValUsoNSRecords =
            chartRecords.Where(x => x.ValUsoNS > 0 || (x.ValUsoAbitativo == 0 && x.ValUsoStrumentale == 0 && x.ValUsoInvestimento == 0)).Select(x => new
            {
                KeyMappature = x.KeyMappature,
                UsoTipologia = "Finalità non specificata",
                ValUsoTotal = x.ValUsoNS
            }).ToList();

            var tableDataGroups = valUsoAbitativoRecords;
            tableDataGroups.AddRange(ValUsoStrumentaleRecords);
            tableDataGroups.AddRange(ValUsoInvestimentoRecords);
            tableDataGroups.AddRange(ValUsoNSRecords);

            var keyMappaturaGroupNames = chartRecords.Select(x => x.KeyMappature).ToList();
            Dictionary<string, int> keyMappaturaGroups = new Dictionary<string, int>();

            int xVal = 1;
            foreach (var keyMap in keyMappaturaGroupNames)
            {
                
                keyMappaturaGroups.Add(keyMap, xVal);
                baseChart.ChartAreas[0].AxisX.CustomLabels.Add((double)xVal - 0.5d, (double)xVal + 0.5d, keyMap);                
                xVal++;
            }

            // Remmato da ES per problemi Ordinamento
            //Dictionary<string, Series> series = new Dictionary<string, Series>();
            //int colorIndex = 0;
            //foreach (var usoTipologia in tableDataGroups.OrderByDescending(x => x.ValUsoTotal).Select(x => x.UsoTipologia).Distinct().ToList())
            //{
            //    var serie = baseChart.Series.Add(usoTipologia);
            //    serie.Type = Dundas.Charting.WebControl.SeriesChartType.StackedColumn;
            //    serie["StackedGroupName"] = "AllSeries";
            //    serie["PixelPointWidth"] = "80";
            //    serie.Color = getColorPDF(usoTipologia);//ChartsColors[colorIndex];
            //    series.Add(usoTipologia, serie);
            //    colorIndex++;
            //}
            // Fine

            // Inserito Nuovo per giusto ordinamento 29/12/2917
            Dictionary<string, Series> series = new Dictionary<string, Series>();
            int colorIndex = 0;
            var serieNames = tableDataGroups.OrderByDescending(x => x.ValUsoTotal).Select(x => x.UsoTipologia).Distinct().ToList();
            Dictionary<string, int> serieItemsOrder = new Dictionary<string, int>()
            {
                //{"Immobili d'uso abitativo", 1 },
                //{"Immobili strumentali",2 },
                //{"Immobili d'investimento", 3 },
                //{"Finalità non specificata", 4 }
                {"Immobili d'uso abitativo", 2 },
                {"Immobili strumentali",3 },
                {"Immobili d'investimento", 4 },
                {"Finalità non specificata", 1 }
            };
            serieNames = serieNames.OrderBy(x => serieItemsOrder[x]).ToList();

            foreach (var usoTipologia in serieNames)
            {
                var serie = baseChart.Series.Add(usoTipologia);
                serie.Type = Dundas.Charting.WebControl.SeriesChartType.StackedColumn;
                serie["StackedGroupName"] = "AllSeries";
                serie["PixelPointWidth"] = "80";
                serie.Color = getColorPDF(usoTipologia);
                series.Add(usoTipologia, serie);
                colorIndex++;
            }
            // Fine Nuovo

            var topLabelSerie = baseChart.Series.Add("topLabelSerie");
            topLabelSerie.Type = Dundas.Charting.WebControl.SeriesChartType.StackedColumn;
            topLabelSerie["StackedGroupName"] = "AllSeries";
            topLabelSerie["PixelPointWidth"] = "80";
            topLabelSerie.Color = Color.Transparent;
            topLabelSerie.Font = new Font("Verdana", 6);
            topLabelSerie.ShowInLegend = false;
            series.Add("topLabelSerie", topLabelSerie);

            #region removing blank gaps ...
            //https://social.msdn.microsoft.com/Forums/en-US/24b22f09-8b23-435c-a6ed-08fc58270239/vertical-gaps-in-stacked-bar-charts?forum=MSWinWebChart
            var data = tableDataGroups.ToList();
            foreach (var keyMappaturaGroup in keyMappaturaGroups)
            {
                foreach (var serie in series)
                {
                    if (tableDataGroups.Where(x => x.KeyMappature == keyMappaturaGroup.Key &&
                                                   x.UsoTipologia == serie.Key).FirstOrDefault() == null)
                    {
                        data.Add(new { KeyMappature = keyMappaturaGroup.Key, UsoTipologia = serie.Key, ValUsoTotal = 0m });
                    }
                }
            }
            data = data.OrderBy(x => x.UsoTipologia).OrderBy(x => x.KeyMappature).ToList();
            #endregion

            foreach (var record in data)
            {
                var addedPoint = series[record.UsoTipologia].Points.AddXY(keyMappaturaGroups[record.KeyMappature], record.ValUsoTotal);
            }

            baseChart.ChartAreas[0].ReCalc();
            baseChart.ChartAreas[0].AxisX.Minimum = 0.5d;
            baseChart.ChartAreas[0].AxisX.Maximum = xVal - 0.5d;

            #region bars top labels
            foreach (var serie in series)
            {
                if (serie.Value.Name == "topLabelSerie")
                {
                    foreach (DataPoint point in serie.Value.Points)
                    {
                        point.SetValueY(baseChart.ChartAreas[0].AxisY.Maximum * 0.15);
                        string keyMappatura = keyMappaturaGroups.Where(x => x.Value == point.XValue).FirstOrDefault().Key;
                        string label = tableDataGroups.Where(x => x.KeyMappature == keyMappatura).Sum(x => x.ValUsoTotal).ToString("##,#", new CultureInfo("es-ES"));
                        if (string.IsNullOrEmpty(label))
                        {
                            label = "-";
                        }
                        point.Label = label;
                    }
                }
            }
            #endregion

            AddElement(customChart);
        }

        private void DrawChart2(List<ChartRecord> chartRecords)
        {
            //chartRecords = chartRecords.OrderByDescending(x => x.ValTotaleTipologia).ToList();
            chartRecords = chartRecords.OrderBy(x => x.OrderInGraph).ThenByDescending(x => x.ValTotaleTipologia).ToList();
            if (chartRecords.Count > 4)
            {
                decimal valUsoAbitativo = 0;
                decimal valUsoStrumentale = 0;
                decimal valUsoInvestimento = 0;
                decimal valUsoNS = 0;

                for (int i = 4; i < chartRecords.Count; i++)
                {
                    valUsoAbitativo += chartRecords[i].ValUsoAbitativo;
                    valUsoStrumentale += chartRecords[i].ValUsoStrumentale;
                    valUsoInvestimento += chartRecords[i].ValUsoInvestimento;
                    valUsoNS += chartRecords[i].ValUsoNS;
                }
                // Commento ES per problemi con Categoria Altro 10/08/2017
                //chartRecords.RemoveRange(4, chartRecords.Count - 4);
                //chartRecords.Add(new ChartRecord()
                //{
                //    ValUsoAbitativo = valUsoAbitativo,
                //    ValUsoInvestimento = valUsoInvestimento,
                //    ValUsoNS = valUsoNS,
                //    ValUsoStrumentale = valUsoStrumentale,
                //    KeyMappature = "Altro",
                //    ValTotaleTipologia = valUsoAbitativo + valUsoInvestimento + valUsoNS + valUsoStrumentale
                //});
            }
            //AddElement(new SpacePDF(195));

            int nLeftStart;
            int nWidth;
            if ((int)chartRecords[0].ValTotaleTipologia < 999999)
            {
                nLeftStart = 335;
                nWidth = 390;
            }
            else
            {
                nLeftStart = 335;
                nWidth = 385;
            }

            var customChart = new CustomChartPDF()
            {
                X = nLeftStart,
                Y = 280
            };
            var baseChart = customChart.ChartBase;
            baseChart.Width = new System.Web.UI.WebControls.Unit(nWidth);
            baseChart.Height = new System.Web.UI.WebControls.Unit(145);
            baseChart.ChartAreas.Add("Default");
            baseChart.ChartAreas["Default"].Area3DStyle.Enable3D = false;
            baseChart.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
            baseChart.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
            baseChart.ChartAreas[0].AxisX.LabelsAutoFit = true;
            baseChart.ChartAreas[0].AxisX.LabelsAutoFitStyle = LabelsAutoFitStyle.WordWrap;
            baseChart.ChartAreas[0].AxisY.LabelStyle.Font = new Font("Verdana", 6);
            baseChart.ChartAreas[0].AxisY.LabelStyle.Format = "€ {#,0}";
            baseChart.ChartAreas[0].AxisX.LabelStyle.Font = new Font("Verdana", 5);
            baseChart.ChartAreas[0].AxisX.MajorTickMark.Enabled = false;
            baseChart.ChartAreas[0].AxisX.MinorTickMark.Enabled = false;
            baseChart.Legends[0].Docking = LegendDocking.Bottom;
            baseChart.Legends[0].Alignment = StringAlignment.Center;
            baseChart.Legends[0].Font = new Font("Verdana", 6);
            baseChart.Legends[0].TextWrapThreshold = 8;
            baseChart.Legends[0].Enabled = false;
            baseChart.CustomizeLegend += BaseChart_CustomizeLegend;

            var valUsoAbitativoRecords =
                chartRecords.Where(x => x.ValUsoAbitativo > 0).Select(x => new
                {
                    KeyMappature = x.KeyMappature,
                    UsoTipologia = "Immobili d'uso abitativo",
                    ValUsoTotal = x.ValUsoAbitativo
                }).ToList();

            var ValUsoStrumentaleRecords =
            chartRecords.Where(x => x.ValUsoStrumentale > 0).Select(x => new
            {
                KeyMappature = x.KeyMappature,
                UsoTipologia = "Immobili strumentali",
                ValUsoTotal = x.ValUsoStrumentale
            }).ToList();

            var ValUsoInvestimentoRecords =
            chartRecords.Where(x => x.ValUsoInvestimento > 0).Select(x => new
            {
                KeyMappature = x.KeyMappature,
                UsoTipologia = "Immobili d'investimento",
                ValUsoTotal = x.ValUsoInvestimento
            }).ToList();


            var ValUsoNSRecords =
            chartRecords.Where(x => x.ValUsoNS > 0 || (x.ValUsoAbitativo == 0 && x.ValUsoStrumentale == 0 && x.ValUsoInvestimento == 0)).Select(x => new
            {
                KeyMappature = x.KeyMappature,
                UsoTipologia = "Finalità non specificata",
                ValUsoTotal = x.ValUsoNS
            }).ToList();

            var tableDataGroups = valUsoAbitativoRecords;
            tableDataGroups.AddRange(ValUsoStrumentaleRecords);
            tableDataGroups.AddRange(ValUsoInvestimentoRecords);
            tableDataGroups.AddRange(ValUsoNSRecords);

            var keyMappaturaGroupNames = chartRecords.Select(x => x.KeyMappature).Distinct().ToList();
            Dictionary<string, int> keyMappaturaGroups = new Dictionary<string, int>();

            int xVal = 1;
            foreach (var keyMap in keyMappaturaGroupNames)
            {
                keyMappaturaGroups.Add(keyMap, xVal);
                baseChart.ChartAreas[0].AxisX.CustomLabels.Add((double)xVal - 0.5d, (double)xVal + 0.5d, keyMap);
                xVal++;
            }

            Dictionary<string, Series> series = new Dictionary<string, Series>();
            int colorIndex = 0;
            var serieNames = tableDataGroups.OrderByDescending(x => x.ValUsoTotal).Select(x => x.UsoTipologia).Distinct().ToList();
            Dictionary<string, int> serieItemsOrder = new Dictionary<string, int>()
            {
                //{"Immobili d'uso abitativo", 1 },
                //{"Immobili strumentali",2 },
                //{"Immobili d'investimento", 3 },
                //{"Finalità non specificata", 4 }
                {"Immobili d'uso abitativo", 2 },
                {"Immobili strumentali",3 },
                {"Immobili d'investimento", 4 },
                {"Finalità non specificata", 1 }

            };
            serieNames = serieNames.OrderBy(x => serieItemsOrder[x]).ToList();

            foreach (var usoTipologia in serieNames)
            {
                var serie = baseChart.Series.Add(usoTipologia);
                serie.Type = Dundas.Charting.WebControl.SeriesChartType.StackedColumn;
                serie["StackedGroupName"] = "AllSeries";
                serie["PixelPointWidth"] = "80";
                serie.Color = getColorPDF(usoTipologia);
                series.Add(usoTipologia, serie);
                colorIndex++;
            }

            var topLabelSerie = baseChart.Series.Add("topLabelSerie");
            topLabelSerie.Type = Dundas.Charting.WebControl.SeriesChartType.StackedColumn;
            topLabelSerie["StackedGroupName"] = "AllSeries";
            topLabelSerie["PixelPointWidth"] = "80";
            topLabelSerie.Color = Color.Transparent;
            topLabelSerie.Font = new Font("Verdana", 6);
            topLabelSerie.ShowInLegend = false;
            series.Add("topLabelSerie", topLabelSerie);

            #region removing blank gaps ...
            //https://social.msdn.microsoft.com/Forums/en-US/24b22f09-8b23-435c-a6ed-08fc58270239/vertical-gaps-in-stacked-bar-charts?forum=MSWinWebChart
            var data = tableDataGroups.ToList();
            foreach (var keyMappaturaGroup in keyMappaturaGroups)
            {
                foreach (var serie in series)
                {
                    if (tableDataGroups.Where(x => x.KeyMappature == keyMappaturaGroup.Key &&
                                                   x.UsoTipologia == serie.Key).FirstOrDefault() == null)
                    {
                        data.Add(new { KeyMappature = keyMappaturaGroup.Key, UsoTipologia = serie.Key, ValUsoTotal = 0m });
                    }
                }
            }
            data = data.OrderBy(x => x.UsoTipologia).OrderBy(x => x.KeyMappature).ToList();
            #endregion

            foreach (var record in data)
            {
                var addedPoint = series[record.UsoTipologia].Points.AddXY(keyMappaturaGroups[record.KeyMappature], record.ValUsoTotal);
            }

            baseChart.ChartAreas[0].ReCalc();
            baseChart.ChartAreas[0].AxisX.Minimum = 0.5d;
            baseChart.ChartAreas[0].AxisX.Maximum = xVal - 0.5d;

            #region bars top labels
            foreach (var serie in series)
            {
                if (serie.Value.Name == "topLabelSerie")
                {
                    foreach (DataPoint point in serie.Value.Points)
                    {
                        point.SetValueY(baseChart.ChartAreas[0].AxisY.Maximum * 0.15);
                        string keyMappatura = keyMappaturaGroups.Where(x => x.Value == point.XValue).FirstOrDefault().Key;
                        string label = tableDataGroups.Where(x => x.KeyMappature == keyMappatura).Sum(x => x.ValUsoTotal).ToString("##,#", new CultureInfo("es-ES"));
                        if (string.IsNullOrEmpty(label))
                        {
                            label = "-";
                        }
                        point.Label = label;
                    }
                }
            }
            #endregion

            AddElement(customChart);
        }

        private void BaseChart_CustomizeLegend(Chart sender, CustomizeLegendEventArgs e)
        {
            var items = e.LegendItems;
            List<LegendItem> legendItems = new List<LegendItem>();
            foreach (LegendItem item in items)
            {
                item.Legend.LegendStyle = LegendStyle.Table;
                legendItems.Add(item);
            }

            Dictionary<string, int> serieItemsOrder = new Dictionary<string, int>()
            {
                {"Immobili d'uso abitativo", 1 },
                {"Immobili strumentali",2 },
                {"Immobili d'investimento", 3 },
                {"Finalità non specificata", 4 }
            };
            legendItems = legendItems.OrderBy(x => serieItemsOrder[x.SeriesName]).ToList();

            e.LegendItems.Clear();
            foreach (var item in legendItems)
            {
                e.LegendItems.Add(item);
            }
        }

        private void DrawChart3(List<ChartRecord> chartRecords)
        {
            Dictionary<string, int> itemsOrder = new Dictionary<string, int>()
            {
                {"Roma/Milano", 1 },
                {"Capoluogo di Provincia",3 },
                {"Capoluogo di Regione", 2 },
                {"Piccolo comune", 4 },
                {"Altro", 5 }
            };
            chartRecords = chartRecords.OrderBy(x => itemsOrder[x.KeyMappature]).ToList();

            int nLeftStart;
            int nWidth;
            if ((int)chartRecords[0].ValTotaleTipologia < 999999)
            {
                nLeftStart = 340;
                nWidth = 385;
            }
            else
            {
                nLeftStart = 335;
                nWidth = 385;
            }

            var customChart = new CustomChartPDF()
            {
                X = nLeftStart,
                Y = 115
            };
            var baseChart = customChart.ChartBase;
            baseChart.Width = new System.Web.UI.WebControls.Unit(nWidth);
            baseChart.Height = new System.Web.UI.WebControls.Unit(136);
            baseChart.ChartAreas.Add("Default");
            baseChart.ChartAreas["Default"].Area3DStyle.Enable3D = false;
            baseChart.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
            baseChart.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
            baseChart.ChartAreas[0].AxisX.LabelsAutoFit = true;
            baseChart.ChartAreas[0].AxisX.LabelsAutoFitStyle = LabelsAutoFitStyle.WordWrap;
            baseChart.ChartAreas[0].AxisY.LabelStyle.Font = new Font("Verdana", 6);
            baseChart.ChartAreas[0].AxisX.LabelStyle.Font = new Font("Verdana", 5);
            baseChart.ChartAreas[0].AxisY.LabelStyle.Format = "€ {#,0}";
            baseChart.ChartAreas[0].AxisX.MajorTickMark.Enabled = false;
            baseChart.ChartAreas[0].AxisX.MinorTickMark.Enabled = false;
            baseChart.Legends[0].Docking = LegendDocking.Bottom;
            baseChart.Legends[0].Alignment = StringAlignment.Center;
            baseChart.Legends[0].Font = new Font("Verdana", 6);
            baseChart.Legends[0].Enabled = false;
            var valUsoAbitativoRecords =
                chartRecords.Where(x => x.ValUsoAbitativo > 0).Select(x => new
                {
                    KeyMappature = x.KeyMappature,
                    UsoTipologia = "Immobili d'uso abitativo",
                    ValUsoTotal = x.ValUsoAbitativo
                }).ToList();

            var ValUsoStrumentaleRecords =
            chartRecords.Where(x => x.ValUsoStrumentale > 0).Select(x => new
            {
                KeyMappature = x.KeyMappature,
                UsoTipologia = "Immobili strumentali",
                ValUsoTotal = x.ValUsoStrumentale
            }).ToList();

            var ValUsoInvestimentoRecords =
            chartRecords.Where(x => x.ValUsoInvestimento > 0).Select(x => new
            {
                KeyMappature = x.KeyMappature,
                UsoTipologia = "Immobili d'investimento",
                ValUsoTotal = x.ValUsoInvestimento
            }).ToList();


            var ValUsoNSRecords =
            chartRecords.Where(x => x.ValUsoNS > 0 || (x.ValUsoAbitativo == 0 && x.ValUsoStrumentale == 0 && x.ValUsoInvestimento == 0)).Select(x => new
            {
                KeyMappature = x.KeyMappature,
                UsoTipologia = "Finalità non specificata",
                ValUsoTotal = x.ValUsoNS
            }).ToList();

            var tableDataGroups = valUsoAbitativoRecords;
            tableDataGroups.AddRange(ValUsoStrumentaleRecords);
            tableDataGroups.AddRange(ValUsoInvestimentoRecords);
            tableDataGroups.AddRange(ValUsoNSRecords);


            var keyMappaturaGroupNames = chartRecords.Select(x => x.KeyMappature).Distinct().ToList();
            Dictionary<string, int> keyMappaturaGroups = new Dictionary<string, int>();

            int xVal = 1;
            foreach (var keyMap in keyMappaturaGroupNames)
            {
                keyMappaturaGroups.Add(keyMap, xVal);
                baseChart.ChartAreas[0].AxisX.CustomLabels.Add((double)xVal - 0.5d, (double)xVal + 0.5d, keyMap);
                xVal++;
            }

            Dictionary<string, Series> series = new Dictionary<string, Series>();

            
            // Vecchio Codice 20171011
            //int colorIndex = 0;
            //foreach (var usoTipologia in tableDataGroups.OrderByDescending(x => x.ValUsoTotal).Select(x => x.UsoTipologia).Distinct().ToList())
            //{
            //    var serie = baseChart.Series.Add(usoTipologia);
            //    serie.Type = Dundas.Charting.WebControl.SeriesChartType.StackedColumn;
            //    serie["StackedGroupName"] = "AllSeries";
            //    serie["PixelPointWidth"] = "80";
            //    serie.Color = getColorPDF(usoTipologia);
            //    series.Add(usoTipologia, serie);
            //    colorIndex++;
            //}

            // Nuovo Codice
            int colorIndex = 0;
            var serieNames = tableDataGroups.OrderByDescending(x => x.ValUsoTotal).Select(x => x.UsoTipologia).Distinct().ToList();
            Dictionary<string, int> serieItemsOrder = new Dictionary<string, int>()
            {
                //{"Immobili d'uso abitativo", 1 },
                //{"Immobili strumentali",2 },
                //{"Immobili d'investimento", 3 },
                //{"Finalità non specificata", 4 }
                {"Immobili d'uso abitativo", 2 },
                {"Immobili strumentali",3 },
                {"Immobili d'investimento", 4 },
                {"Finalità non specificata", 1 }

            };
            serieNames = serieNames.OrderBy(x => serieItemsOrder[x]).ToList();

            foreach (var usoTipologia in serieNames)
            {
                var serie = baseChart.Series.Add(usoTipologia);
                serie.Type = Dundas.Charting.WebControl.SeriesChartType.StackedColumn;
                serie["StackedGroupName"] = "AllSeries";
                serie["PixelPointWidth"] = "80";
                serie.Color = getColorPDF(usoTipologia);
                series.Add(usoTipologia, serie);
                colorIndex++;
            }
            // Fine Nuovo Codice


            var topLabelSerie = baseChart.Series.Add("topLabelSerie");
            topLabelSerie.Type = Dundas.Charting.WebControl.SeriesChartType.StackedColumn;
            topLabelSerie["StackedGroupName"] = "AllSeries";
            topLabelSerie["PixelPointWidth"] = "80";
            topLabelSerie.Color = Color.Transparent;
            topLabelSerie.Font = new Font("Verdana", 6);
            topLabelSerie.ShowInLegend = false;
            series.Add("topLabelSerie", topLabelSerie);

            #region removing blank gaps ...
            //https://social.msdn.microsoft.com/Forums/en-US/24b22f09-8b23-435c-a6ed-08fc58270239/vertical-gaps-in-stacked-bar-charts?forum=MSWinWebChart
            var data = tableDataGroups.ToList();
            foreach (var keyMappaturaGroup in keyMappaturaGroups)
            {
                foreach (var serie in series)
                {
                    if (tableDataGroups.Where(x => x.KeyMappature == keyMappaturaGroup.Key &&
                                                   x.UsoTipologia == serie.Key).FirstOrDefault() == null)
                    {
                        data.Add(new { KeyMappature = keyMappaturaGroup.Key, UsoTipologia = serie.Key, ValUsoTotal = 0m });
                    }
                }
            }
            data = data.OrderBy(x => x.UsoTipologia).OrderBy(x => x.KeyMappature).ToList();
            #endregion

            foreach (var record in data)
            {
                var addedPoint = series[record.UsoTipologia].Points.AddXY(keyMappaturaGroups[record.KeyMappature], record.ValUsoTotal);
            }

            baseChart.ChartAreas[0].ReCalc();
            baseChart.ChartAreas[0].AxisX.Minimum = 0.5d;
            baseChart.ChartAreas[0].AxisX.Maximum = xVal - 0.5d;

            #region bars top labels
            foreach (var serie in series)
            {
                if (serie.Value.Name == "topLabelSerie")
                {
                    foreach (DataPoint point in serie.Value.Points)
                    {
                        point.SetValueY(baseChart.ChartAreas[0].AxisY.Maximum * 0.15);
                        string keyMappatura = keyMappaturaGroups.Where(x => x.Value == point.XValue).FirstOrDefault().Key;
                        string label = tableDataGroups.Where(x => x.KeyMappature == keyMappatura).Sum(x => x.ValUsoTotal).ToString("##,#", new CultureInfo("es-ES"));
                        if (string.IsNullOrEmpty(label))
                        {
                            label = "-";
                        }
                        point.Label = label;
                    }
                }
            }
            #endregion

            AddElement(customChart);
        }

        private void DrawChart4(List<ChartRecord> chartRecords)
        {
            Dictionary<string, int> itemsOrder = new Dictionary<string, int>()
            {
                {"Centrale", 1 },
                {"Semicentrale",2 },
                {"Periferica/Suburbana", 3 },
                {"Rurale", 4 },
                {"n.d.", 5 }
            };
            chartRecords = chartRecords.OrderBy(x => itemsOrder[x.KeyMappature]).ToList();

            int nLeftStart;
            int nWidth;
            if ((int)chartRecords[0].ValTotaleTipologia < 999999)
            {
                nLeftStart = 340;
                nWidth = 385;
            }
            else
            {
                nLeftStart = 335;
                nWidth = 385;
            }

            var customChart = new CustomChartPDF()
            {
                X = nLeftStart,
                Y = 280
            };
            var baseChart = customChart.ChartBase;
            baseChart.Width = new System.Web.UI.WebControls.Unit(nWidth);
            baseChart.Height = new System.Web.UI.WebControls.Unit(165);
            baseChart.ChartAreas.Add("Default");
            baseChart.ChartAreas["Default"].Area3DStyle.Enable3D = false;
            baseChart.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
            baseChart.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
            baseChart.ChartAreas[0].AxisX.LabelsAutoFit = true;
            baseChart.ChartAreas[0].AxisX.LabelsAutoFitStyle = LabelsAutoFitStyle.WordWrap;
            baseChart.ChartAreas[0].AxisY.LabelStyle.Font = new Font("Verdana", 6);
            baseChart.ChartAreas[0].AxisX.LabelStyle.Font = new Font("Verdana", 5);
            baseChart.ChartAreas[0].AxisY.LabelStyle.Format = "€ {#,0}";
            baseChart.ChartAreas[0].AxisX.MajorTickMark.Enabled = false;
            baseChart.ChartAreas[0].AxisX.MinorTickMark.Enabled = false;
            baseChart.Legends[0].Docking = LegendDocking.Bottom;
            baseChart.Legends[0].Alignment = StringAlignment.Center;
            baseChart.Legends[0].Font = new Font("Verdana", 6);
            baseChart.Legends[0].Enabled = false;
            baseChart.Legends[0].TextWrapThreshold = 8;
            baseChart.CustomizeLegend += BaseChart_CustomizeLegend;

            var valUsoAbitativoRecords =
                chartRecords.Where(x => x.ValUsoAbitativo > 0).Select(x => new
                {
                    KeyMappature = x.KeyMappature,
                    UsoTipologia = "Immobili d'uso abitativo",
                    ValUsoTotal = x.ValUsoAbitativo
                }).ToList();

            var ValUsoStrumentaleRecords =
            chartRecords.Where(x => x.ValUsoStrumentale > 0).Select(x => new
            {
                KeyMappature = x.KeyMappature,
                UsoTipologia = "Immobili strumentali",
                ValUsoTotal = x.ValUsoStrumentale
            }).ToList();

            var ValUsoInvestimentoRecords =
            chartRecords.Where(x => x.ValUsoInvestimento > 0).Select(x => new
            {
                KeyMappature = x.KeyMappature,
                UsoTipologia = "Immobili d'investimento",
                ValUsoTotal = x.ValUsoInvestimento
            }).ToList();


            var ValUsoNSRecords =
            chartRecords.Where(x => x.ValUsoNS > 0 || (x.ValUsoAbitativo == 0 && x.ValUsoStrumentale == 0 && x.ValUsoInvestimento == 0)).Select(x => new
            {
                KeyMappature = x.KeyMappature,
                UsoTipologia = "Finalità non specificata",
                ValUsoTotal = x.ValUsoNS
            }).ToList();

            var tableDataGroups = valUsoAbitativoRecords;
            tableDataGroups.AddRange(ValUsoStrumentaleRecords);
            tableDataGroups.AddRange(ValUsoInvestimentoRecords);
            tableDataGroups.AddRange(ValUsoNSRecords);

            var keyMappaturaGroupNames = chartRecords.Select(x => x.KeyMappature).Distinct().ToList();
            Dictionary<string, int> keyMappaturaGroups = new Dictionary<string, int>();

            int xVal = 1;
            foreach (var keyMap in keyMappaturaGroupNames)
            {
                keyMappaturaGroups.Add(keyMap, xVal);
                baseChart.ChartAreas[0].AxisX.CustomLabels.Add((double)xVal - 0.5d, (double)xVal + 0.5d, keyMap.Replace("/", "/\n"));
                xVal++;
            }

            Dictionary<string, Series> series = new Dictionary<string, Series>();
            int colorIndex = 0;
            var serieNames = tableDataGroups.OrderByDescending(x => x.ValUsoTotal).Select(x => x.UsoTipologia).Distinct().ToList();
            Dictionary<string, int> serieItemsOrder = new Dictionary<string, int>()
            {
                //{"Immobili d'uso abitativo", 1 },
                //{"Immobili strumentali",2 },
                //{"Immobili d'investimento", 3 },
                //{"Finalità non specificata", 4 }
                {"Immobili d'uso abitativo", 2 },
                {"Immobili strumentali",3 },
                {"Immobili d'investimento", 4 },
                {"Finalità non specificata", 1 }

            };
            serieNames = serieNames.OrderBy(x => serieItemsOrder[x]).ToList();


            foreach (var usoTipologia in serieNames)
            {
                var serie = baseChart.Series.Add(usoTipologia);
                serie.Type = Dundas.Charting.WebControl.SeriesChartType.StackedColumn;
                serie["StackedGroupName"] = "AllSeries";
                serie["PixelPointWidth"] = "80";
                serie.Color = getColorPDF(usoTipologia);
                series.Add(usoTipologia, serie);
                colorIndex++;
            }

            var topLabelSerie = baseChart.Series.Add("topLabelSerie");
            topLabelSerie.Type = Dundas.Charting.WebControl.SeriesChartType.StackedColumn;
            topLabelSerie["StackedGroupName"] = "AllSeries";
            topLabelSerie["PixelPointWidth"] = "80";
            topLabelSerie.Color = Color.Transparent;
            topLabelSerie.Font = new Font("Verdana", 6);
            topLabelSerie.ShowInLegend = false;
            series.Add("topLabelSerie", topLabelSerie);

            #region removing blank gaps ...
            //https://social.msdn.microsoft.com/Forums/en-US/24b22f09-8b23-435c-a6ed-08fc58270239/vertical-gaps-in-stacked-bar-charts?forum=MSWinWebChart
            var data = tableDataGroups.ToList();
            foreach (var keyMappaturaGroup in keyMappaturaGroups)
            {
                foreach (var serie in series)
                {
                    if (tableDataGroups.Where(x => x.KeyMappature == keyMappaturaGroup.Key &&
                                                   x.UsoTipologia == serie.Key).FirstOrDefault() == null)
                    {
                        data.Add(new { KeyMappature = keyMappaturaGroup.Key, UsoTipologia = serie.Key, ValUsoTotal = 0m });
                    }
                }
            }
            data = data.OrderBy(x => x.UsoTipologia).OrderBy(x => x.KeyMappature).ToList();
            #endregion

            foreach (var record in data)
            {
                var addedPoint = series[record.UsoTipologia].Points.AddXY(keyMappaturaGroups[record.KeyMappature], record.ValUsoTotal);
            }

            baseChart.ChartAreas[0].ReCalc();
            baseChart.ChartAreas[0].AxisX.Minimum = 0.5d;
            baseChart.ChartAreas[0].AxisX.Maximum = xVal - 0.5d;

            #region bars top labels
            foreach (var serie in series)
            {
                if (serie.Value.Name == "topLabelSerie")
                {
                    foreach (DataPoint point in serie.Value.Points)
                    {
                        point.SetValueY(baseChart.ChartAreas[0].AxisY.Maximum * 0.15);
                        string keyMappatura = keyMappaturaGroups.Where(x => x.Value == point.XValue).FirstOrDefault().Key;
                        string label = tableDataGroups.Where(x => x.KeyMappature == keyMappatura).Sum(x => x.ValUsoTotal).ToString("##,#", new CultureInfo("es-ES"));
                        if (string.IsNullOrEmpty(label))
                        {
                            label = "-";
                        }
                        point.Label = label;
                    }
                }
            }
            #endregion

            AddElement(customChart);
        }

        private void DrawLegend(int positionX, int positionY)
        {
            ColorPDF coloriUsoAbitativo = new ColorPDF(207, 220, 210);
            ColorPDF coloriStrumentale = new ColorPDF(167, 192, 168);
            ColorPDF coloriInvestimento = new ColorPDF(115, 152, 109);
            ColorPDF coloriNonSpecificata = new ColorPDF(245, 245, 220);
            var originalX = positionX;
            int xOffset = 100;//150;
            var legendaUsoAbitativoRettangolo = new RectanglePDF(positionX, 12, 17, coloriUsoAbitativo) { AutoIncrementYWritable = false, Y = positionY };
            var legendaUsoAbitativoTesto = new FormattedTextAreaPDF(string.Format("{0}", "Immobili<br>d'uso abitativo"), positionX + 25) { FontSize = 6, AutoIncrementYWritable = false, Y = positionY-0.5F };
            
            positionX += xOffset;
            var legendaStrumentaleRettangolo = new RectanglePDF(positionX, 12, 17, coloriStrumentale) { AutoIncrementYWritable = false, Y = positionY };
            var legendaStrumentaleTesto = new FormattedTextAreaPDF(string.Format("{0}", "Immobili<br>strumentali"), positionX + 25) { FontSize = 6, AutoIncrementYWritable = true, Y = positionY - 0.5F };

            //positionY += 15;
            //positionX=  originalX;
            positionX += xOffset;
            var legendaInvestimentoRettangolo = new RectanglePDF(positionX, 12, 17, coloriInvestimento) { AutoIncrementYWritable = false, Y = positionY };
            var legendaInvestimentoTesto = new FormattedTextAreaPDF(string.Format("{0}", "Immobili<br>d'investimento"), positionX + 25) { FontSize = 6, AutoIncrementYWritable = true, Y = positionY - 0.5F };

            positionX += xOffset;
            var legendaNonSpecificataRettangolo = new RectanglePDF(positionX, 12, 17, coloriNonSpecificata) { AutoIncrementYWritable = false, Y = positionY };
            var legendaNonSpecificataTesto = new FormattedTextAreaPDF(string.Format("{0}", "Finalità<br>non specificata"), positionX + 25) { FontSize = 6, AutoIncrementYWritable = true, Y = positionY - 0.5F };
            
            AddElement(legendaUsoAbitativoRettangolo);
            AddElement(legendaUsoAbitativoTesto);
            AddElement(legendaStrumentaleRettangolo);
            AddElement(legendaStrumentaleTesto);
            AddElement(legendaInvestimentoRettangolo);
            AddElement(legendaInvestimentoTesto);
            AddElement(legendaNonSpecificataRettangolo);
            AddElement(legendaNonSpecificataTesto);
        }
        public virtual Stream getImageFromStored()
        {
            var parametri = new List<Parametro>
            {
                new Parametro
                {
                    Direction = ParameterDirection.Input,
                    DbType = DbType.Int32,
                    ParameterName = "chiaveClientePB",
                    Value = EnvironmentFacade.ReportEnvironment.Cliente.Chiave
                },
                new Parametro
                {
                    Direction = ParameterDirection.Input,
                    DbType = DbType.Int32,
                    ParameterName = "chiaveNucleo",
                    Value = 0
                }
            };

            var data = DataAccess.ExecuteDataSetStoredProcedure(DBProvider.SqlServerConsulenzaUnica, "REP_ImmobiliareMonitoraggio_S14_MapDistrGeografica_Image", parametri);
            
            byte[] imageBytes = (byte[])data.Tables[0].Rows[0][0];
            MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
            ms.Write(imageBytes, 0, imageBytes.Length);
            return ms;
        }

        private class ChartRecord
        {
            public int ChiaveTipoChart { get; set; }
            public string KeyMappature { get; set; }
            public decimal ValTotaleTipologia { get; set; }
            public decimal ValUsoAbitativo { get; set; }
            public decimal ValUsoStrumentale { get; set; }
            public decimal ValUsoInvestimento { get; set; }
            public decimal ValUsoNS { get; set; }
            public string UsoTipologia { get; set; }
            public decimal NumImmobili { get; set; }
            public string OrderInGraph { get; set; }
        }

        private Color getColorPDF(string usoTipologia) {

            switch (usoTipologia) { 
                case "Immobili d'uso abitativo":
                    return Color.FromArgb(206, 219, 209);
                case "Immobili strumentali":
                    return Color.FromArgb(167, 192, 168);
                case "Immobili d'investimento":
                    return Color.FromArgb(114, 152, 110);
                case "Finalità non specificata":
                    return Color.FromArgb(245, 245, 220);
                default:
                    return Color.FromArgb(206, 219, 209);
            }
        }
    }
}
