using System;
using System.Linq;
using Consulenza.ReportWriter.Business;
using Consulenza.ReportWriter.Business.OBJ_PDF;
using ceTe.DynamicPDF;
using System.Data;
using Consulenza.ReportCommon;
using System.Collections.Generic;
using Consulenza.ExternalServices;
using Consulenza.ReportWriter.Manager.Integration;


namespace Consulenza.ReportWriter.Manager.Section.Immobiliare.MonitoraggioNucleo
{
    /// <summary>
    /// Scheda di stima parametrica del valore (id 39)
    /// </summary>
    //public class S7 : Monitoraggio.S7
    //{
    //    public S7(EnvironmentFacade environmentFacade, int idSection)
    //        : base(environmentFacade, idSection)
    //    {
    //    }
    //}

    public class S7 : Entity.Section
    {
        //private bool _assenzaTipologiaDiritto;
        //private bool _assenzaQuotaDiritto;


        public S7(EnvironmentFacade environmentFacade, int idSection)
            : base(environmentFacade, idSection)
        {
            try
            {
                Draw();
            }
            catch (Exception ex)
            {
                SectionLogger.Write("S7", 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 data = dataset.Tables[1];

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

            foreach (var indice in indiciPagina)
            {
                #region Text

                string paragrafoSx = "";
                string paragrafoDx = "";

                if (_text.AsEnumerable().Where(x => x.Field<int>("idREP_IMM_MON_Pagina") == indice).Count() > 0)
                {
                    var testo = _text.AsEnumerable().Where(x => x.Field<int>("idREP_IMM_MON_Pagina") == indice).ToList();
                    foreach (var row in testo)
                    {
                        if (row["posizione"].Equals("L"))
                            paragrafoSx = "<B>" + row.Field<string>("titolo") + "</B><br><br>";
                        else
                            paragrafoDx = "<B>" + row.Field<string>("titolo") + "</B><br><br>";

                        for (int i = 1; i <= 15; i++)
                            if (row["posizione"].Equals("L"))
                                paragrafoSx += row.Field<string>("testo" + i) != null ? "<p>" + row.Field<string>("testo" + i) + "</p><br>" : "";
                            else
                                paragrafoDx += row.Field<string>("testo" + i) != null ? "<p>" + row.Field<string>("testo" + i) + "</p><br>" : "";
                    }

                    var testoSx = new FormattedTextAreaPDF(paragrafoSx, 35, 370) { AutoIncrementYWritable = false, Y = 55, FontSize = 9, FontColor = ColorPDF.Immobiliare_Grigio_TestoStandard, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                    //var testoDx = new FormattedTextAreaPDF(paragrafoDx, 430, 320) { AutoIncrementYWritable = false, FontSize = 9, FontColor = ColorPDF.Immobiliare_Grigio_TestoStandard, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                    var testoDx = new FormattedTextAreaPDF(paragrafoDx, 35, 370) { AutoIncrementYWritable = false, FontSize = 9, FontColor = ColorPDF.Immobiliare_Grigio_TestoStandard, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };

                    if (data.AsEnumerable().Where(x => x.Field<int>("idREP_IMM_MON_Pagina") == indice).Count() > 0)
                    {
                        TablePDF table = null;
                        FormattedTextAreaPDF titolo = null;
                        foreach (var row in data.AsEnumerable())
                        {
                            DataTable tabella = new DataTable();

                            tabella.Columns.Add("Key");
                            tabella.Columns.Add("Value");
                            for (int i = 1; i <= 10; i++)
                            {
                                if (row["keyItem" + i] != null && row["keyItem" + i].ToString() != "")
                                {
                                    tabella.Rows.Add(row["keyItem" + i], row["valueItem" + i]);
                                }
                            }


                            switch (row["idTipologia"].ToString())
                            {
                                case "1":
                                    titolo = new FormattedTextAreaPDF("<br>" + row.Field<string>("descrizione"), 430, 300) { AutoIncrementYWritable = true, FontSize = 12, FontColor = ColorPDF.Immobiliare_Grigio_TitoloPiccolo, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                                    table = new TablePDF(430, tabella)
                                    {
                                        Style = Style.Immobiliare,
                                        AlternateRow = false,
                                        HeaderHeight = 25,
                                        RowHeight = 15,
                                        Footer = false,
                                        ShowBorderLastLine = true,
                                        //AdditionalSpaceBetweenHeadersAndTable = 5.0F,
                                        HeaderTextVerticalAlign = VerticalAlignmentType.Basso
                                    };

                                    table.Columns.Add(new ColumnPDF("Key1", 120, HorizontalAlignmentType.Sinistra, false, false, 8, ColumnType.Testo, "Key", "") { HeaderFontColor = new ColorPDF(92, 89, 81), HeaderFontSize = 8, DeltaYContent = 1 });
                                    table.Columns.Add(new ColumnPDF("Value1", 80, HorizontalAlignmentType.Centrato, false, false, 8, ColumnType.Objectpdf, "Value", "<B>Aspettativa</B>") { HeaderFontColor = new ColorPDF(92, 89, 81), HeaderFontSize = 9, DeltaYContent = 1 });
                                    AddElement(testoSx);

                                    int i = 0;
                                    foreach (DataRow r in tabella.Rows)
                                    {
                                        ImagePDF imageSymbol = new ImagePDF(0, 1, tabella.Rows[i]["Value"].ToString())
                                        {
                                            DeltaY = 3,
                                            //DeltaY = tabella.Rows[i]["Value"].ToString().Contains("horizontal") ? -2 : -3,
                                            Scale = 0.1f
                                        };

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

                                    AddElement(new SpacePDF(29));//TO-DO con aggiunta di note e legenda
                                    AddElement(titolo);
                                    AddElement(new SpacePDF(18));
                                    AddElement(table);
                                    AddElement(new SpacePDF(11));
                                    addLegend(row);
                                    AddElement(new SpacePDF(-8));
                                    break;
                                case "2":
                                    //titolo = new FormattedTextAreaPDF("<br>" + row.Field<string>("descrizione"), 35, 330) { Y = EnvironmentFacade.RendererFacade.YUpperLimit + 195, FontSize = 12, FontColor = ColorPDF.Immobiliare_Grigio_TitoloPiccolo, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                                    //table = new TablePDF(35, tabella)
                                    titolo = new FormattedTextAreaPDF("<br>" + row.Field<string>("descrizione"), 430, 320) { Y = EnvironmentFacade.RendererFacade.YUpperLimit + 195, FontSize = 12, FontColor = ColorPDF.Immobiliare_Grigio_TitoloPiccolo, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                                    table = new TablePDF(430, tabella)
                                    {
                                        Style = Style.Immobiliare,
                                        AlternateRow = false,
                                        HeaderHeight = 15,
                                        RowHeight = 5,
                                        Footer = false,
                                        ShowBorderLastLine = true,
                                        HeaderTextVerticalAlign = VerticalAlignmentType.Basso,
                                    };

                                    table.Columns.Add(new ColumnPDF("Key2", 120, HorizontalAlignmentType.Sinistra, false, false, 8, ColumnType.Testo, "Key", "<B>Città</B>") { HeaderFontColor = new ColorPDF(92, 89, 81), HeaderFontSize = 9, HeaderVerticalAlignment = VerticalAlignmentType.Centrato, DeltaYContent = 5 });
                                    table.Columns.Add(new ColumnPDF("Value2", 80, HorizontalAlignmentType.Centrato, false, false, 8, ColumnType.Objectpdf, "Value", "<B>Aspettativa</B>") { HeaderFontColor = new ColorPDF(92, 89, 81), HeaderFontSize = 9, HeaderVerticalAlignment = VerticalAlignmentType.Centrato });

                                    int j = 0;
                                    foreach (DataRow r in tabella.Rows)
                                    {
                                        ImagePDF imageSymbol = new ImagePDF(0, 1, tabella.Rows[j]["Value"].ToString())
                                        {
                                            DeltaY = 3,
                                            //DeltaY = tabella.Rows[i]["Value"].ToString().Contains("horizontal") ? -2 : -3,
                                            Scale = 0.1f
                                        };

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

                                    var x1Linea = 30;
                                    var x2Linea = 750;
                                    var lineaVerticaleSeparazione = new LinePDF(x1Linea, x2Linea, 0.5F, ColorPDF.Immobiliare_Marrone);

                                    // Dati Statici 20181005
                                    //AddElement(new SpacePDF(5));
                                    //AddElement(titolo);
                                    //AddElement(new SpacePDF(12));
                                    //AddElement(testoDx);
                                    //AddElement(new SpacePDF(-20));
                                    //AddElement(lineaVerticaleSeparazione);
                                    //AddElement(new SpacePDF(38));
                                    //AddElement(table);
                                    //addLegend(row);

                                    AddElement(new SpacePDF(-25));
                                    AddElement(titolo);
                                    AddElement(new SpacePDF(22));
                                    AddElement(testoDx);
                                    AddElement(lineaVerticaleSeparazione);
                                    AddElement(new SpacePDF(38));
                                    AddElement(table);
                                    addLegend(row);
                                    AddElement(new SpacePDF(-5));

                                    // End
                                    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]), 430, 300) { AutoIncrementYWritable = false, Y = 212, FontSize = 6, FontColor = ColorPDF.Nero, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                                        AddElement(nota);
                                    }

                                    break;


                                default:
                                    break;

                            }
                        }
                    }

                    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, 680) { Y = EnvironmentFacade.RendererFacade.YLowerLimit - 15 - (5 * count), FontSize = 6, FontColor = ColorPDF.Nero, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                        var nota = new FormattedTextAreaPDF(getNota(_text.Rows[0]), 60, 300) { Y = EnvironmentFacade.RendererFacade.YLowerLimit - 13 - (5 * count), FontSize = 6, FontColor = ColorPDF.Nero, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                        AddElement(nota);
                    }

                #endregion
                }
            }
        }

        protected void addLegend(DataRow data)
        {
            //int xLegenda = data.Field<string>("posizione").Equals("R") ? 680 : 320;
            //int xLegenda2 = data.Field<string>("posizione").Equals("R") ? 672 : 312;
            //int xLegendaTesto = data.Field<string>("posizione").Equals("R") ? 690 : 330;
            //int yLegenda = data.Field<string>("posizione").Equals("R") ? 134 : 400;

            // Inversione Carnevali 20181003
            int xLegenda = 680;
            int xLegenda2 = 672;
            int xLegendaTesto = 690;
            int yLegenda = data.Field<string>("posizione").Equals("R") ? 134 : 400;

            int legendWidth = 90;
            int legendHeight = 60;

            if (!data.Field<string>("posizione").Equals("R"))
                AddElement(new ResetterYPDF(300));

            //AddElement(new RectanglePDF(legendHeight, legendWidth, new ColorPDF(217, 217, 217)) { X = xLegenda, AutoIncrementYWritable = false, DeltaY = 2 });
            // Sfondo Bianco
            AddElement(new SpacePDF(1));
            AddElement(new RectanglePDF(legendHeight, legendWidth, new ColorPDF(255, 255, 255)) { X = xLegenda, AutoIncrementYWritable = false, Y = yLegenda, DeltaY = 2, BorderColor = ColorPDF.Immobiliare_Grigio_TitoloPiccolo });

            List<string> columnName = new List<string>();
            for (int index = 1; index <= 10; index++)
            {
                columnName.Add(data.Field<string>("keyLegenda" + index));
                columnName.Add(data.Field<string>("valueLegenda" + index));
            }
            columnName.RemoveAll(item => item == null);


            foreach (string name in columnName)
            {
                if (name.Contains(".png"))
                {
                    if (name.Contains("2"))
                        AddElement(new ImagePDF(xLegenda2, 0.15F, name) { DeltaY = 5F, Y = yLegenda, AutoIncrementYWritable = false });
                    else
                        AddElement(new ImagePDF(xLegenda, 0.15F, name) { DeltaY = 5F, Y = yLegenda, AutoIncrementYWritable = false });
                    //xLegenda += name.Contains("2") ? 20 : 10;
                    //xLegenda += 10 ;
                }
                else
                {
                    var ftaNomeLabel = new FormattedTextAreaPDF
                    {
                        Text = name,
                        FontColor = new ColorPDF(92, 89, 81),
                        DeltaY = 4F,
                        AutoIncrementYWritable = false,
                        X = xLegendaTesto,
                        Y = yLegenda,
                        FontSize = 7,
                        FontBold = true
                    };

                    //xLegenda += (ftaNomeLabel.Text.Length * 5) + (10 - ftaNomeLabel.Text.Length);
                    yLegenda += 9;
                    //xLegenda -= 10;
                    //xLegenda -= name.Contains("2") ? 20 : 10;
                    AddElement(ftaNomeLabel);
                }
            }       
        }

        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;
        }

        /// <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_S7_Aspettative_Future", parametri);

        }
    }

}
