using System;
using Consulenza.ReportWriter.Business.OBJ_PDF;
using Consulenza.ReportWriter.Business;
using ceTe.DynamicPDF;
using System.Data;
using System.Linq;
using Consulenza.ReportCommon;
using System.Collections.Generic;
using Consulenza.ReportWriter.Business.Entity;
using Consulenza.ReportWriter.Business.CHART_PDF;
using ceTe.DynamicPDF.PageElements;
using System.Web;
namespace Consulenza.ReportWriter.Manager.Section.Immobiliare.Monitoraggio
{
    /// <summary>
    /// Dettaglio fabbricati (id 37)
    /// </summary>
    public class S5 : Entity.Section
    {
        public S5(EnvironmentFacade environmentFacade, int idSection)
            : base(environmentFacade, idSection)
        {
            try
            {
                Draw();
            }
            catch (Exception ex)
            {
                SectionLogger.Write("S5", 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 sealed void Draw()
        {
            var dataset = GetDataSet();
            List<ChartRecord> chartItems = GetChartData(dataset);
            Dictionary<string, string> legendItems = GetLegendItems(dataset);
            string chartHeader = (string)dataset.Tables[1].Rows[0]["descrizione"];
            DrawChart(chartItems, legendItems, chartHeader);
            var _text = dataset.Tables[0];
            var dataGrafici = dataset.Tables[1];
            var width = 340;
            List<int> indiciPagina = _text.AsEnumerable()
                .Select(z => z.Field<int>("idREP_IMM_MON_Pagina")).Distinct().ToList();

            foreach (var indice in indiciPagina)
            {
                var data = _text.AsEnumerable().Where(x => x.Field<int>("idREP_IMM_MON_Pagina") == indice).ToList();
                foreach (var row in data)
                {
                    int i = 1;

                    string paragrafoSx = "";
                    string paragrafoIntero = "<B>" + row.Field<string>("titolo") + "</B><br><br>";

                    for (i = 1; i <= 15; i++)
                    {
                        if (i == 1)
                            paragrafoIntero += row.Field<string>("testo" + i) != null ? " <p> " + row.Field<string>("testo" + i).Replace("&lt;br/&gt;", "<br>") + " </p><br><br>" : "";
                        else
                            paragrafoSx += row.Field<string>("testo" + i) != null ? "<p>" + row.Field<string>("testo" + i) + "</p><br>" : "";
                    }
                    AddElement(new ResetterYPDF(60));
                    var testo = new FormattedTextAreaPDF(paragrafoIntero, 35, width * 2 + 35) { FontSize = 9, FontColor = ColorPDF.Immobiliare_Grigio_TestoStandard, AutoIncrementYWritable = true, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                    AddElement(testo);

                    if (paragrafoSx != null)
                    {
                        /***************************** Modifica per parti statiche semestrale 10/2020 - Pino ******************************************************/
                        //AddElement(new SpacePDF(5));
                        AddElement(new SpacePDF(-5));
                        /******************************************************************************************************************************/
                        var testoSx = new FormattedTextAreaPDF(paragrafoSx, 35, width / 2 + 35) { FontSize = 9, FontColor = ColorPDF.Immobiliare_Grigio_TestoStandard, AutoIncrementYWritable = true, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                        AddElement(testoSx);

                    }
                }

                if (getNota(_text.Rows[0]).Length > 0)
                {
                    string testoNota = getNota(_text.Rows[0]);
                    int count = testoNota.Replace("<br>", "\t").Count(x => x == '\t');
                    var nota = new FormattedTextAreaPDF(getNota(_text.Rows[0]), 60, width * 2) { Y = EnvironmentFacade.RendererFacade.YLowerLimit - 13 - (5 * count), FontSize = 6, FontColor = ColorPDF.Nero, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                    AddElement(nota);
                }

            }
        }

        protected string getNota(DataRow row)
        {
            string nota = "";
            for (int i = 1; i <= 5; i++)
                if (row.Field<string>("nota" + i) != null)
                    nota += row.Field<string>("nota" + i) + "<br>";
            return nota;
        }

        private void DrawChart(List<ChartRecord> chartItems, Dictionary<string, string> legendItems, string header)
        {
            var itemsTogether = chartItems.Select(x => x.LineMax).ToList();
            itemsTogether.AddRange(chartItems.Select(x => x.LineMin).ToList());
            int chartXPosition = 305;

            int minValue = (int)itemsTogether.Min(x => x);
            int maxValue = (int)itemsTogether.Max(x => x);
            int minAxisY = 1000;
            int maxAxisY = 6000;  //5500
            int intervalValueY = 500;
            GetChartSpecifications(10, minValue, maxValue, 5, out minAxisY, out maxAxisY, out intervalValueY);
            minAxisY = 1000;
            maxAxisY = 6000;    //5500
            intervalValueY = 500;

            int axisYLineWidth = 2;
            int minAxisX = 0;
            int maxAxisX = chartItems.Count() * 2; // od 0 zaczynajac, lecimy 1, 3, 5, ...
            int intervalValueX = 1;
            float width = 440;
            float height = 195;
            float spaceForLabel = width / chartItems.Count;

            AddElement(new SpacePDF(121));
            var chart = new CombinationPDF(chartXPosition, 1)
            {
                Height = height,
                Width = width,
                ChartBaseWidth = width,
                ChartBaseHeight = height,
                AutoIncrementYWritable = false,
                ShowLineAxisY = false,
                DontCalculateMaxAndMinAxisY = true,
                MaximumValueAxisY = maxAxisY,
                MinimumValueAxisY = minAxisY,
                IntervalNumberAxisY = (maxAxisY - minAxisY) / intervalValueY,
                StartFromZeroAxisY = true,
                InnerChartDeltaY = 7f,
                ShowLabelAxisY = true,
                MaximumValueAxisX = maxAxisX,
                StartFromZeroAxisX = true,
                IntervalNumberAxisX = (maxAxisX - minAxisX) / intervalValueX,
                ShowLabelAxisX = false,
                ShowLineAxisX = false
            };

            //axis Y
            chart.ChartBase.ChartAreas[0].AxisY.MinorGrid.Enabled = true;
            chart.ChartBase.ChartAreas[0].AxisY.MinorGrid.Interval = intervalValueY;
            chart.ChartBase.ChartAreas[0].AxisY.MinorGrid.LineWidth = axisYLineWidth;
            chart.ChartBase.ChartAreas[0].AxisY.MinorGrid.LineColor = System.Drawing.Color.FromArgb(217, 217, 217);


            //axis X
            chart.ChartBase.ChartAreas[0].AxisX.Interval = intervalValueX;
            chart.SeriesCollection = new List<Serie>();

            int rowIndex = 1;
            float currentLabelXPosition = chart.X;
            foreach (ChartRecord record in chartItems)
            {
                #region grayLine
                Serie serie = new Serie()
                {
                    Name = string.Format("serie{0}", rowIndex),
                    Type = Dundas.Charting.WebControl.SeriesChartType.Line,
                    BorderWidth = 7,
                    Color = new ColorPDF(166, 166, 166),
                    MarkerSize = 20,
                    MarkerStyle = Dundas.Charting.WebControl.MarkerStyle.Diamond
                };
                serie.Points.Add(new Point
                {
                    Color = new ColorPDF(166, 166, 166),
                    Values = new ValuesPointXY(rowIndex, (double)record.LineMax),
                    FontSizeLabelAxisY = 7,
                    FontBoldLabelAxisY = false,
                    ShowLabelAxisY = true
                });
                serie.Points.Add(new Point
                {
                    Color = new ColorPDF(166, 166, 166),
                    Values = new ValuesPointXY(rowIndex, (double)record.LineMin),
                    FontSizeLabelAxisY = 7,
                    FontBoldLabelAxisY = false,
                    ShowLabelAxisY = true
                });
                #endregion

                #region brownRectangle
                Serie serie2 = new Serie()
                {
                    Name = string.Format("serieBrown{0}", rowIndex),
                    Type = Dundas.Charting.WebControl.SeriesChartType.Line,
                    BorderWidth = 7,
                    Color = new ColorPDF(174, 150, 81),
                    MarkerImage = "brownRectangle.png"
                    //MarkerSize = 20,
                    //MarkerStyle = Dundas.Charting.WebControl.MarkerStyle.Square
                };
                serie2.Points.Add(new Point
                {
                    Color = new ColorPDF(174, 150, 81),
                    Values = new ValuesPointXY(rowIndex, (double)record.Price1),
                    FontSizeLabelAxisY = 7,
                    FontBoldLabelAxisY = false,
                    ShowLabelAxisY = true
                });
                #endregion

                #region greenRectangle
                Serie serie3 = new Serie()
                {
                    Name = string.Format("serieGreen{0}", rowIndex),
                    Type = Dundas.Charting.WebControl.SeriesChartType.Line,
                    BorderWidth = 7,
                    Color = new ColorPDF(114, 152, 110),
                    MarkerImage = "greenRectangle.png"
                    //MarkerSize = 20,
                    //MarkerStyle = Dundas.Charting.WebControl.MarkerStyle.Square
                };
                serie3.Points.Add(new Point
                {
                    Color = new ColorPDF(114, 152, 110),
                    Values = new ValuesPointXY(rowIndex, (double)record.Price2),
                    FontSizeLabelAxisY = 7,
                    FontBoldLabelAxisY = false,
                    ShowLabelAxisY = true
                });
                #endregion

                chart.SeriesCollection.Add(serie);
                chart.SeriesCollection.Add(serie2);
                chart.SeriesCollection.Add(serie3);

                #region labels axis X
                var labelXCity = new FormattedTextAreaPDF(record.City, currentLabelXPosition, spaceForLabel) { AutoIncrementYWritable = false, DeltaY = chart.Height + 42, FontSize = 6.96f };
                var styleUsed = new FormattedTextAreaStyle(EnvironmentFacade.ReportEnvironment.FontFamily, labelXCity.FontSize, false);// { Bold = element.FontBold };
                float textWidth = styleUsed.GetFont().GetTextWidth(record.City, styleUsed.Font.Size);
                labelXCity.Width = textWidth;
                float offsetToAdd = (spaceForLabel - textWidth) / 2;
                labelXCity.X += offsetToAdd;
                AddElement(labelXCity);
                #endregion

                #region months axisX
                var labelXMonth = new FormattedTextAreaPDF(record.Month, currentLabelXPosition, spaceForLabel) { AutoIncrementYWritable = false, DeltaY = chart.Height + 54, FontSize = 7f, FontBold = true, FontColor = new ColorPDF(92, 89, 81) };
                var styleUsedMonth = new FormattedTextAreaStyle(EnvironmentFacade.ReportEnvironment.FontFamily, labelXMonth.FontSize, false) { Bold = labelXMonth.FontBold };
                float textWidthMonth = styleUsed.GetFont().GetTextWidth(record.Month, styleUsedMonth.Font.Size) + 5;
                labelXMonth.Width = textWidthMonth;
                float offsetToAddMonth = (spaceForLabel - textWidthMonth) / 2;
                labelXMonth.X += offsetToAddMonth;
                AddElement(labelXMonth);
                #endregion
                currentLabelXPosition += spaceForLabel;
                rowIndex += 2;
            }
            //new FormattedTextAreaStyle(EnvironmentFacade.ReportEnvironment.FontFamily, 6.96f, false) { Bold = true };
            AddElement(new FormattedTextAreaPDF("Tempi medi di vendita", chartXPosition - 56, 50)
            {
                FontBold = true,
                FontSize = 6.96f,
                DeltaY = chart.Height + 48,                
                TextHorizontalAlign = TextAlign.Right,
                FontColor = new ColorPDF(92, 89, 81)
            });
            AddElement(new FormattedTextAreaPDF(header, chartXPosition - 20) { AutoIncrementYWritable = false, FontSize = 10.5f, FontColor = new ColorPDF(152, 149, 133), DeltaY = -18, DeltaX = -25 });
            AddElement(new FormattedTextAreaPDF("€/mq", chartXPosition - 55)
            {
                TextVerticalDirection = true,
                DeltaY = chart.Height / 2 + 28
            });


            AddElement(chart);
            AddElement(new ResetterYPDF());

            #region legend

            //int legendX = 505;
            int legendX = 260;
            int legendY = 413;

            int legendWidth = 240;
            int legendHeight = 23;

            // Original
            //AddElement(new RectanglePDF(legendHeight, legendWidth, new ColorPDF(217, 217, 217)) { Y = legendY, X = legendX, AutoIncrementYWritable = false });

            //AddElement(new ImagePDF(legendX + 5, 0.38f, "greenRectangle.png") { Y = legendY + 10, AutoIncrementYWritable = false });
            //AddElement(new FormattedTextAreaPDF("<b>" + legendItems["anno1"] + "</b>", legendX + 26) { Y = legendY + 6, AutoIncrementYWritable = false, FontBold = false, FontSize = 8 });

            //AddElement(new ImagePDF(legendX + 65, 0.38f, "brownRectangle.png") { Y = legendY + 10, AutoIncrementYWritable = false });
            //AddElement(new FormattedTextAreaPDF("<b>"+legendItems["anno2"]+"</b>", legendX + 86) { Y = legendY + 6, AutoIncrementYWritable = false, FontBold = false, FontSize = 8 });

            //AddElement(new ImagePDF(legendX + 115, 0.15f, "legendItem.png") { Y = legendY+3, AutoIncrementYWritable = false });
            //AddElement(new FormattedTextAreaPDF("<b>" + legendItems["range"] + "</b>", legendX + 125) { Y = legendY + 4.9F, AutoIncrementYWritable = false, FontBold = false, FontSize = 6 });

            // Sfondo Bianco
            AddElement(new RectanglePDF(legendHeight, legendWidth, new ColorPDF(255, 255, 255)) { Y = legendY, X = legendX, AutoIncrementYWritable = false, BorderColor = ColorPDF.Immobiliare_Grigio_TitoloPiccolo, BorderWidth = 0.2f });

            AddElement(new ImagePDF(legendX + 5, 0.38f, "greenRectangle.png") { Y = legendY + 10, AutoIncrementYWritable = false });
            AddElement(new FormattedTextAreaPDF("<b>" + legendItems["anno1"] + "</b>", legendX + 26) { Y = legendY + 6, AutoIncrementYWritable = false, FontBold = false, FontSize = 8 });

            AddElement(new ImagePDF(legendX + 65, 0.38f, "brownRectangle.png") { Y = legendY + 10, AutoIncrementYWritable = false });
            AddElement(new FormattedTextAreaPDF("<b>" + legendItems["anno2"] + "</b>", legendX + 86) { Y = legendY + 6, AutoIncrementYWritable = false, FontBold = false, FontSize = 8 });

            AddElement(new ImagePDF(legendX + 115, 0.15f, "legendItem_2.png") { Y = legendY + 3, AutoIncrementYWritable = false });
            AddElement(new FormattedTextAreaPDF("<b>" + legendItems["range"] + "</b>", legendX + 125) { Y = legendY + 4.9F, AutoIncrementYWritable = false, FontBold = false, FontSize = 6 });

            #endregion
        }

        /// <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 = "IdReport",
                        Value = EnvironmentFacade.ReportEnvironment.ReportId
                    },
                    new Parametro
                    {
                        Direction = ParameterDirection.Input,
                        DbType = DbType.Int32,
                        ParameterName = "IdSezione",
                        Value = IdSection
                    }
                };
            return DataAccess.ExecuteDataSetStoredProcedure(DBProvider.SqlServerReportModeler, "REP_Monitoraggio_Immobiliare_S3_S4_Focus", parametri);
        }

        private class ChartRecord
        {
            public decimal LineMin { get; set; }
            public decimal LineMax { get; set; }
            public decimal Price1 { get; set; }
            public decimal Price2 { get; set; }
            public string Month { get; set; }
            public string City { get; set; }
        }


        private Dictionary<string, string> GetLegendItems(DataSet dataSet)
        {
            Dictionary<string, string> results = new Dictionary<string, string>();
            DataRow row = dataSet.Tables[1].Rows[0];

            for (int i = 0; i < dataSet.Tables[1].Columns.Count; i++)
            {
                DataColumn column = dataSet.Tables[1].Columns[i];
                if (column.ColumnName.ToLower().StartsWith("keylegenda") && row[column.ColumnName] != DBNull.Value)
                {
                    results.Add((string)row[column.ColumnName], (string)row[i + 1]);
                }
            }
            return results;
        }
        private List<ChartRecord> GetChartData(DataSet dataSet)
        {
            List<ChartRecord> results = new List<ChartRecord>();
            foreach (DataRow row in dataSet.Tables[1].Rows)
            {
                ChartRecord record = new ChartRecord()
                {
                    LineMax = (decimal)row["valMax"],
                    LineMin = (decimal)row["valMin"],
                    Month = (string)row["mesi"],
                    Price1 = (decimal)row["prezzo1"],
                    Price2 = (decimal)row["prezzo2"],
                    City = (string)row["chiave"]
                };
                results.Add(record);
            }
            return results;
        }

        private void GetChartSpecifications(int intervalsCount, decimal realMinValue, decimal realMaxValue,
                                            int marginPercentageValue,
                                            out int minValue, out int maxValue,
                                            out int intervalValue)
        {
            int difference = (int)realMaxValue - (int)realMinValue;
            minValue = (int)realMinValue - (difference * marginPercentageValue / 100);
            maxValue = (int)realMaxValue + (difference * marginPercentageValue / 100);
            minValue = minValue.Round((int)Math.Pow(10, minValue.ToString().Length - 2));
            maxValue = maxValue.Round((int)Math.Pow(10d, maxValue.ToString().Length - 2));
            intervalValue = (maxValue - minValue) / intervalsCount;
        }
    }
    public static class MathExtensions
    {
        public static int Round(this int i, int nearest)
        {
            if (nearest <= 0 || nearest % 10 != 0)
                throw new ArgumentOutOfRangeException("nearest", "Must round to a positive multiple of 10");

            return (i + 5 * nearest / 10) / nearest * nearest;
        }
    }
}
