using System;
using System.Linq;
using Consulenza.ReportWriter.Business;
using Consulenza.ReportWriter.Business.OBJ_PDF;
using System.Data;
using Consulenza.ReportCommon;
using System.Collections.Generic;
using Consulenza.ReportWriter.Business.Entity;

namespace Consulenza.ReportWriter.Manager.Section.Immobiliare.MonitoraggioNucleo
{
    /// <summary>
    ///  Dettaglio terreni (id 38)
    /// </summary>
    //public class S6 : Monitoraggio.S6
    //{
    //    public S6(EnvironmentFacade environmentFacade, int idSection)
    //        : base(environmentFacade, idSection)
    //    {
    //    }
    //}
    public class S6 : Entity.Section
    {
        public S6(EnvironmentFacade environmentFacade, int idSection)
            : base(environmentFacade, idSection)
        {
            try
            {
                Draw();
            }
            catch (Exception ex)
            {
                SectionLogger.Write("S6", 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();
            var _text = dataset.Tables[0];
            var dataTabella = dataset.Tables[1];

            List<int> indiciPagina = dataTabella.AsEnumerable()
                .Select(z => z.Field<int>("idREP_IMM_MON_Pagina")).Distinct().ToList();

            int numeroPagina = 1;
            var width = 340;

            foreach (var indice in indiciPagina)
            {
                #region Text
                AddElement(new PagePDF(PagePDF.PagePDFType.Generic));

                string paragrafo = "";
                if (_text.AsEnumerable().Where(x => x.Field<int>("idREP_IMM_MON_Pagina") == indice).Count() > 0)
                {
                    var data = _text.AsEnumerable().Where(x => x.Field<int>("idREP_IMM_MON_Pagina") == indice).ToList();
                    foreach (var row in data)
                    {
                        paragrafo = "<B>" + row.Field<string>("titolo") + "</B><br><br>";

                        for (int i = 1; i <= 15; i++)
                            paragrafo += row.Field<string>("testo" + i) != null ? "<p>" + row.Field<string>("testo" + i) + "</p><br>" : "";
                    }

                    var testo = new FormattedTextAreaPDF(paragrafo, 35, 715) { AutoIncrementYWritable = true, FontSize = 9, FontColor = ColorPDF.Immobiliare_Grigio_TestoStandard, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };

                    AddElement(new ResetterYPDF(55));
                    AddElement(testo);
                    AddElement(new SpacePDF(10));
                }

                #endregion

                if (dataTabella.AsEnumerable().Where(x => x.Field<int>("idREP_IMM_MON_Pagina") == indice).Count() > 0)
                {
                    var tabella = dataTabella.AsEnumerable().Where(x => x.Field<int>("idREP_IMM_MON_Pagina") == indice).CopyToDataTable();
                    switch (numeroPagina)
                    {
                        case 1:
                            // Dati Statici 20181005
                            //var testo = new FormattedTextAreaPDF("<br>" + tabella.Rows[0].Field<string>("descrizione"), 35, 650) { FontSize = 10, FontColor = ColorPDF.Immobiliare_Grigio_TitoloGrande, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                            //var x1Linea = 35;
                            //var x2Linea = 750;
                            //var lineaVerticaleSeparazione = new LinePDF(x1Linea, x2Linea, 0.5F, ColorPDF.Immobiliare_Grigio_TitoloPiccolo) { AutoIncrementYWritable = true };

                            //AddElement(new SpacePDF(-10));
                            //AddElement(testo);
                            //AddElement(new SpacePDF(5));
                            //AddElement(lineaVerticaleSeparazione);

                            // End

                            var testo = new FormattedTextAreaPDF(tabella.Rows[0].Field<string>("descrizione"), 35, 650) { FontSize = 10, FontColor = ColorPDF.Immobiliare_Grigio_TitoloGrande, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                            var x1Linea = 35;
                            var x2Linea = 750;
                            var lineaVerticaleSeparazione = new LinePDF(x1Linea, x2Linea, 0.5F, ColorPDF.Immobiliare_Grigio_TitoloPiccolo) { AutoIncrementYWritable = true };

                            AddElement(new SpacePDF(-8));
                            AddElement(testo);
                            AddElement(new SpacePDF(5));
                            AddElement(lineaVerticaleSeparazione);


                            DataTable header = new DataTable();
                            header.Columns.Add("Trend");
                            header.Columns.Add("Acquisto");
                            header.Columns.Add("Affitto");
                            header.Columns.Add("Redditivita");

                            header.Rows.Add("Trend vivacità<br>compravendite*",
                                            "Prezzo medio<br>Acquisto** (€/mq)",
                                            "Prezzo medio<br>Affitto** (€/mq)",
                                            "Redditività media lorda su base<br>annua (%)");

                            var tableHeader = new TablePDF(125, header)
                            {
                                Style = Style.Immobiliare,
                                AlternateRow = false,
                                Header = false,
                                Footer = false,
                                ShowBorderLastLine = false,
                                HideFirstSeparationLine = true,
                                DrawLineHeaderUP = false
                            };

                            tableHeader.Columns.Add(new ColumnPDF("Trend", 145, HorizontalAlignmentType.Centrato, false, true, 8, ColumnType.Testo, "Trend", "") { /*VerticalAlignment = VerticalAlignmentType.Basso,*/ DeltaYContent = 5 });
                            tableHeader.Columns.Add(new ColumnPDF("Acquisto", 160, HorizontalAlignmentType.Centrato, false, true, 8, ColumnType.Testo, "Acquisto", "") { /*VerticalAlignment = VerticalAlignmentType.Basso,*/ DeltaYContent = 5 });
                            tableHeader.Columns.Add(new ColumnPDF("Affitto", 160, HorizontalAlignmentType.Centrato, false, true, 8, ColumnType.Testo, "Affitto", "") { /*VerticalAlignment = VerticalAlignmentType.Basso,*/ DeltaYContent = 5 });
                            tableHeader.Columns.Add(new ColumnPDF("Redditivita", 160, HorizontalAlignmentType.Centrato, false, true, 8, ColumnType.Testo, "Redditivita", "") { /*VerticalAlignment = VerticalAlignmentType.Basso,*/ DeltaYContent = 5 });

                            AddElement(tableHeader);

                            var table = new TablePDF(35, tabella)
                            {
                                Style = Style.Immobiliare,
                                AlternateRow = false,
                                HeaderHeight = 15,
                                Footer = false,
                                ShowBorderLastLine = true,
                                AdditionalSpaceBetweenHeadersAndTable = 5.0F,
                                HeaderTextVerticalAlign = VerticalAlignmentType.Basso,
                                DrawLineHeaderUP = false,
                                HideFirstSeparationLine = true,
                                IndexesOfRowLinesToIgnoreSeparators = new List<int>() { 1 }
                            };
                            var headerLine = new LinePDF(155, 750, 0.5F, ColorPDF.Immobiliare_Grigio_TitoloPiccolo) { AutoIncrementYWritable = false, DeltaY = 1 };
                            AddElement(headerLine);

                            table.Columns.Add(new ColumnPDF("Città", 90, HorizontalAlignmentType.Sinistra, false, false, 9, ColumnType.Testo, "citta", "Città") { HeaderFontSize = 8, HeaderFontColor = ColorPDF.Immobiliare_Grigio_TitoloPiccolo });
                            table.Columns.Add(new ColumnPDF("Residenziale", 145, HorizontalAlignmentType.Centrato, false, false, 7, ColumnType.Objectpdf, "trend", "Residenziale") { HeaderFontSize = 8, ScaleColumnTypeImage = 2.0F, HeaderFontColor = ColorPDF.Immobiliare_Grigio_TitoloPiccolo });
                            table.Columns.Add(new ColumnPDF("Centro1", 80, HorizontalAlignmentType.Centrato, false, false, 7, ColumnType.Testo, "centroMedioAcquisto", "Centro") { HeaderFontSize = 8, HeaderFontColor = ColorPDF.Immobiliare_Grigio_TitoloPiccolo });
                            table.Columns.Add(new ColumnPDF("Periferia1", 80, HorizontalAlignmentType.Centrato, false, false, 7, ColumnType.Testo, "periferiaMedioAcquisto", "Periferia") { HeaderFontSize = 8, HeaderFontColor = ColorPDF.Immobiliare_Grigio_TitoloPiccolo });
                            table.Columns.Add(new ColumnPDF("Centro2", 80, HorizontalAlignmentType.Centrato, false, false, 7, ColumnType.Testo, "centroMedioAffitto", "Centro") { HeaderFontSize = 8, HeaderFontColor = ColorPDF.Immobiliare_Grigio_TitoloPiccolo });
                            table.Columns.Add(new ColumnPDF("Periferia2", 80, HorizontalAlignmentType.Centrato, false, false, 7, ColumnType.Testo, "periferiaMedioAffitto", "Periferia") { HeaderFontSize = 8, HeaderFontColor = ColorPDF.Immobiliare_Grigio_TitoloPiccolo });
                            table.Columns.Add(new ColumnPDF("Centro3", 80, HorizontalAlignmentType.Centrato, false, false, 7, ColumnType.Testo, "centroRedditoMedio", "Centro") { HeaderFontSize = 8, HeaderFontColor = ColorPDF.Immobiliare_Grigio_TitoloPiccolo });
                            table.Columns.Add(new ColumnPDF("Periferia3", 80, HorizontalAlignmentType.Centrato, false, false, 7, ColumnType.Testo, "periferiaRedditoMedio", "Periferia") { HeaderFontSize = 8, HeaderFontColor = ColorPDF.Immobiliare_Grigio_TitoloPiccolo });
                            int i = 0;
                            foreach (DataRow r in tabella.Rows)
                            {
                                ImagePDF imageSymbol = new ImagePDF(0, 1, tabella.Rows[i]["trend"].ToString())
                                {
                                    DeltaX = tabella.Rows[i]["trend"].ToString().Contains("horizontal") ? -8 : -7,
                                    DeltaY = tabella.Rows[i]["trend"].ToString().Contains("horizontal") ? 2 : 2,
                                    //DeltaY = 2,
                                    Scale = tabella.Rows[i]["trend"].ToString().Contains("horizontal") ? 0.35f : 0.50f
                                };

                                table.Cells[1, i].ValueObjectList.Add(imageSymbol);
                                i++;
                            }
                            AddElement(table);

                            addLegend();

                            //#region Nota Tabella OLD
                            //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();
                            //    if (count == 0)
                            //        //nota = new FormattedTextAreaPDF(getNota(_text.Rows[0]), 60, width * 2) { Y = EnvironmentFacade.RendererFacade.YLowerLimit - 18, FontSize = 6, FontColor = ColorPDF.Nero, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                            //        nota = new FormattedTextAreaPDF(getNota(_text.Rows[0]), 60, width * 2) { Y = EnvironmentFacade.RendererFacade.YLowerLimit - 18 - 5, FontSize = 6, FontColor = ColorPDF.Nero, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                            //    else
                            //        nota = new FormattedTextAreaPDF(getNota(_text.Rows[0]), 60, width * 2) { Y = EnvironmentFacade.RendererFacade.YLowerLimit - 19 - (6 * count), FontSize = 6, FontColor = ColorPDF.Nero, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                            //    AddElement(nota);
                            //}
                            //#endregion

                            #region Nota Tabella
                            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();
                                if (count == 0)
                                    //nota = new FormattedTextAreaPDF(getNota(_text.Rows[0]), 60, width * 2) { Y = EnvironmentFacade.RendererFacade.YLowerLimit - 18, FontSize = 6, FontColor = ColorPDF.Nero, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                                    nota = new FormattedTextAreaPDF(getNota(_text.Rows[0]), 60, width * 2) { Y = EnvironmentFacade.RendererFacade.YLowerLimit - 13 - 5, FontSize = 6, FontColor = ColorPDF.Nero, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                                else
                                    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);

                                string testoNotaTabella = getNota(_text.Rows[0]);
                                int countTabella = testoNotaTabella.Replace("<br>", "\t").Count(x => x == '\t');
                                var notaTabella = new FormattedTextAreaPDF();
                                if (countTabella == 0)
                                    //nota = new FormattedTextAreaPDF(getNota(_text.Rows[0]), 60, width * 2) { Y = EnvironmentFacade.RendererFacade.YLowerLimit - 18, FontSize = 6, FontColor = ColorPDF.Nero, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                                    notaTabella = new FormattedTextAreaPDF(getNotaTabella(_text.Rows[0]), 205, width * 2) { Y = EnvironmentFacade.RendererFacade.YLowerLimit - 55 - 5, FontSize = 6, FontColor = ColorPDF.Nero, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                                else
                                    notaTabella = new FormattedTextAreaPDF(getNotaTabella(_text.Rows[0]), 205, width * 2) { Y = EnvironmentFacade.RendererFacade.YLowerLimit - 56 - (6 * count), FontSize = 6, FontColor = ColorPDF.Nero, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };

                                AddElement(notaTabella);

                            }
                            #endregion

                            numeroPagina++;
                            break;

                        default:
                            if (dataTabella.AsEnumerable().Where(x => x.Field<int>("idREP_IMM_MON_Pagina") == indice).Count() > 0
                            && dataTabella.AsEnumerable().Where(x => x.Field<string>("descrizioneImage") == null).Count() > 0)
                            {
                                foreach (var image in dataTabella.AsEnumerable().Where(x => x.Field<int>("idREP_IMM_MON_Pagina") == indice).ToList())
                                {
                                    string titoloStatico = image.Field<string>("descrizioneImage") + "<br>";
                                    var titoloGrafico = new FormattedTextAreaPDF(titoloStatico, 50, width * 2) { FontSize = 10, FontColor = ColorPDF.Immobiliare_Grigio_TitoloPiccolo, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                                    var cartina = new ImagePDF(35, 0.465F, image.Field<string>("bytesImage") + ".jpeg");
                                    AddElement(new ResetterYPDF(50));
                                    AddElement(titoloGrafico);
                                    AddElement(cartina);
                                    if (getNota(image).Length > 0)
                                    {
                                        //var nota = new FormattedTextAreaPDF(getNota(image), 60, width * 2) { Y = EnvironmentFacade.RendererFacade.YLowerLimit - 20, FontSize = 6, FontColor = ColorPDF.Nero, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                                        var nota = new FormattedTextAreaPDF(getNota(image), 60, width * 2) { Y = EnvironmentFacade.RendererFacade.YLowerLimit - 18, FontSize = 6, FontColor = ColorPDF.Nero, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                                        AddElement(nota);
                                    }
                                }


                            }
                            break;


                    }

                }

            }
        }

        protected void addLegend()
        {
            int xLegenda = 35;
            int legendWidth = 160;
            int legendHeight = 15;

            AddElement(new SpacePDF(5));

            // Original
            //AddElement(new RectanglePDF(legendHeight, legendWidth, new ColorPDF(217, 217, 217)) { X = xLegenda, AutoIncrementYWritable = false });
            AddElement(new RectanglePDF(legendHeight, legendWidth, new ColorPDF(255, 255, 255))
            {
                X = xLegenda,
                AutoIncrementYWritable = false,
                BorderColor = ColorPDF.Immobiliare_Grigio_TitoloPiccolo,
                BorderWidth = 0.2f
            });

            // Original
            //AddElement(new ImagePDF(xLegenda, 0.50F, "upArrow_grigio.png") { DeltaY = 4F, AutoIncrementYWritable = false, DeltaX = 4F });
            AddElement(new ImagePDF(xLegenda, 0.50F, "upArrow.png") { DeltaY = 4F, AutoIncrementYWritable = false, DeltaX = 4F });

            xLegenda += 20;
            var ftaNomeLabel = new FormattedTextAreaPDF
            {
                Text = "In crescita",
                FontColor = ColorPDF.Nero,
                DeltaX = 1F,
                DeltaY = 4F,
                AutoIncrementYWritable = false,
                X = xLegenda,
                FontSize = 7
            };

            xLegenda += 40;// + (ftaNomeLabel.Text.Length * 5) + (10 - ftaNomeLabel.Text.Length);
            AddElement(ftaNomeLabel);

            // Original
            //AddElement(new ImagePDF(xLegenda, 0.35F, "horizontalArrow_grigio.png") { DeltaY = 5.2F, AutoIncrementYWritable = false, DeltaX = 4F });
            AddElement(new ImagePDF(xLegenda, 0.35F, "horizontalArrow.png") { DeltaY = 5.2F, AutoIncrementYWritable = false, DeltaX = 4F });


            xLegenda += 20;
            ftaNomeLabel = new FormattedTextAreaPDF
            {
                Text = "Stabile",
                FontColor = ColorPDF.Nero,
                DeltaX = 1F,
                DeltaY = 4F,
                AutoIncrementYWritable = false,
                X = xLegenda,
                FontSize = 7
            };
            xLegenda += 25;// + (ftaNomeLabel.Text.Length * 5) + (10 - ftaNomeLabel.Text.Length);
            AddElement(ftaNomeLabel);

            // Original
            //AddElement(new ImagePDF(xLegenda, 0.50F, "downArrow_grigio.png") { DeltaY = 4F, AutoIncrementYWritable = false, DeltaX = 4F });
            AddElement(new ImagePDF(xLegenda, 0.50F, "downArrow.png") { DeltaY = 4F, AutoIncrementYWritable = false, DeltaX = 4F });

            xLegenda += 20;
            ftaNomeLabel = new FormattedTextAreaPDF
            {
                Text = "In calo",
                FontColor = ColorPDF.Nero,
                DeltaX = 1F,
                DeltaY = 4F,
                AutoIncrementYWritable = false,
                X = xLegenda,
                FontSize = 7
            };
            AddElement(ftaNomeLabel);
        }

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

        protected string getNotaTabella(DataRow row)
        {
            string nota = "";
            for (int i = 1; i <= 5; i++)
                if (row.Field<string>("nota" + i) != null && row.Field<string>("nota" + i).Substring(0, 5) != "Fonti")
                    nota += row.Field<string>("nota" + i) + "<br>";
            return nota;
        }

        /// <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
                    // Impostato a -1 per prendere quello dei Report Monitoraggio Immobiliare
                    Value = EnvironmentFacade.ReportEnvironment.ReportId - 1
                },
                new Parametro
                {
                    Direction = ParameterDirection.Input,
                    DbType = DbType.Int32,
                    ParameterName = "IdSezione",
                    Value = IdSection
                }
            };


            return DataAccess.ExecuteDataSetStoredProcedure(DBProvider.SqlServerReportModeler, "REP_Monitoraggio_Immobiliare_S6_Focus_Territoriale", parametri);

        }
    }
}
