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;

//namespace Consulenza.ReportWriter.Manager.Section.Immobiliare.MonitoraggioNucleo
//{
//    /// <summary>
//    /// Distribuzione geografica Fabbricati (id 35)
//    /// </summary>
//    public class S3 : Immobiliare.Monitoraggio.S3
//    {

//        public S3(EnvironmentFacade environmentFacade, int idSection)
//            : base(environmentFacade, idSection)
//        {
//        }
//    }
//}

namespace Consulenza.ReportWriter.Manager.Section.Immobiliare.MonitoraggioNucleo
{
    /// <summary>
    /// Distribuzione geografica Fabbricati (id 35)
    /// </summary>
    public class S3 : Entity.Section
    {

        public S3(EnvironmentFacade environmentFacade, int idSection)
            : base(environmentFacade, idSection)
        {
            try
            {
                Draw();
            }
            catch (Exception ex)
            {
                SectionLogger.Write("S3", ex.Message, SectionLoggerMessageLevel.E, EnvironmentFacade.ReportEnvironment);
            }
        }


        // OLD CODE
        ///// <summary>
        ///// Scheda2. Patrimonio immobiliare –Sintesi (distribuzione del patrimonio complessivo del cliente diviso per tipologia e cointestatari)
        ///// </summary>
        //protected override sealed void Draw()
        //{
        //    var width = 345;
        //    var xSx = 35;
        //    var xDx = 400;

        //    FormattedTextAreaPDF testoSx = null;
        //    FormattedTextAreaPDF testoDx = null;

        //    var _text = GetTextSet();

        //    List<int> indiciPagina = _text.Tables[0].AsEnumerable()
        //        .Select(z => z.Field<int>("idREP_IMM_MON_Pagina")).Distinct().ToList();

        //    int i = -1;

        //    foreach (var indice in indiciPagina)
        //    {
        //        string paragrafoSx;
        //        string paragrafoDx;
        //        i++;

        //        AddElement(new PagePDF(PagePDF.PagePDFType.Generic));
        //        var data = _text.Tables[0].AsEnumerable().Where(x => x.Field<int>("idREP_IMM_MON_Pagina") == indice).ToList();

        //        foreach (var row in data)
        //        {
        //            paragrafoSx = paragrafoDx = "";

        //            if (!row.Field<string>("posizione").Equals("R"))
        //                paragrafoSx += "<B>" + row.Field<string>("titolo") + "</B><br><br>";
        //            else
        //                paragrafoDx += "<B>" + row.Field<string>("titolo") + "</B><br><br>";

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

        //            // SPLIT PARAGRAFO
        //            if (paragrafoSx.Contains("SPLITPARAGRAPH"))
        //            {
        //                var listaSplit = StringExtensions.SplitAtOccurence(paragrafoSx, "SPLITPARAGRAPH", 1);
        //                paragrafoSx = listaSplit[0] + "</p>";
        //                paragrafoDx = "<p>";
        //                listaSplit.RemoveRange(0, 1);
        //                foreach (var stringa in listaSplit)
        //                    paragrafoDx += stringa;
        //            }

        //            testoSx = new FormattedTextAreaPDF(paragrafoSx.Replace("<p></p><br>", ""), 35, width) { AutoIncrementYWritable = false, FontColor = ColorPDF.Immobiliare_Grigio_TestoStandard, FontSize = 9, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
        //            testoDx = new FormattedTextAreaPDF(paragrafoDx.Replace("<p></p><br>", "<br><br>"), 410, width) { AutoIncrementYWritable = false, FontColor = ColorPDF.Immobiliare_Grigio_TestoStandard, FontSize = 9, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };

        //            AddElement(new ResetterYPDF(55 + (i * 5)));
        //            AddElement(testoSx);
        //            addFiller(row, 3);
        //            if (paragrafoDx != "")
        //            {
        //                AddElement(new ResetterYPDF((paragrafoDx.ToLower().Contains("<b>") ? 55 : 50) + (i * 5)));
        //                if (indice == 4)
        //                    AddElement(new SpacePDF(20));

        //                AddElement(testoDx);
        //                addFiller(row, 4);
        //            }
        //        }

        //        if (getNota(_text.Tables[0].AsEnumerable().Where(x => x.Field<int>("idREP_IMM_MON_Pagina") == indice).ToList()[0]).Length > 0)
        //        {
        //            string testoNota = getNota(_text.Tables[0].AsEnumerable().Where(x => x.Field<int>("idREP_IMM_MON_Pagina") == indice).ToList()[0]);
        //            IEnumerable<DataRow> rows = _text.Tables[0].AsEnumerable()
        //                    .Where(x => x.Field<string>("notaGraf1") != null);
        //            int count = testoNota.Replace("<br>", "\t").Count(x => x == '\t');
        //            var nota = new FormattedTextAreaPDF(testoNota, 60, width * 2) { AutoIncrementYWritable = false, Y = EnvironmentFacade.RendererFacade.YLowerLimit - 18 - (5 * count), FontSize = 6, FontColor = ColorPDF.Nero, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
        //            AddElement(nota);
        //        }

        //    }

        //}

        protected override sealed void Draw()
        {
            var width = 345;
            var xSx = 35;
            var xDx = 400;

            FormattedTextAreaPDF testoSx = null;
            FormattedTextAreaPDF testoDx = null;

            var _text = GetTextSet();

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

            int i = -1;

            foreach (var indice in indiciPagina)
            {
                string paragrafoSx;
                string paragrafoDx;
                i++;

                AddElement(new PagePDF(PagePDF.PagePDFType.Generic));
                var data = _text.Tables[0].AsEnumerable().Where(x => x.Field<int>("idREP_IMM_MON_Pagina") == indice).ToList();


                foreach (var row in data)
                {
                    paragrafoSx = paragrafoDx = "";
                    if (!row.Field<string>("posizione").Equals("R"))
                        paragrafoSx += "<B>" + row.Field<string>("titolo") + "</B><br><br>";
                    else
                        paragrafoDx += "<B>" + row.Field<string>("titolo") + "</B><br><br>";

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

                    // SPLIT PARAGRAFO
                    if (paragrafoSx.Contains("SPLITPARAGRAPH"))
                    {
                        var listaSplit = StringExtensions.SplitAtOccurence(paragrafoSx, "SPLITPARAGRAPH", 1);
                        paragrafoSx = listaSplit[0] + "</p>";
                        paragrafoDx = "<p>";
                        listaSplit.RemoveRange(0, 1);
                        foreach (var stringa in listaSplit)
                            paragrafoDx += stringa;

                    }

                    testoSx = new FormattedTextAreaPDF(paragrafoSx.Replace("<p></p><br>", ""), 35, width) { AutoIncrementYWritable = false, FontColor = ColorPDF.Immobiliare_Grigio_TestoStandard, FontSize = 9.26F, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                    testoDx = new FormattedTextAreaPDF(paragrafoDx.Replace("<p></p><br>", "<br><br>"), 405, width) { AutoIncrementYWritable = false, FontColor = ColorPDF.Immobiliare_Grigio_TestoStandard, FontSize = 9.26F, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };

                    //AddElement(new ResetterYPDF(55+(i*5)));
                    if (indice == 3)
                        AddElement(new ResetterYPDF(45 + (i * 5)));
                    else
                        AddElement(new ResetterYPDF(40 + (i * 5)));

                    AddElement(testoSx);
                    addFiller(row, 3);
                    if (paragrafoDx != "")
                    {
                        //AddElement(new ResetterYPDF((paragrafoDx.ToLower().Contains("<b>") ? 55 : 50)+(i * 5)));
                        if (indice == 3)
                            AddElement(new ResetterYPDF((paragrafoDx.ToLower().Contains("<b>") ? 94 : 40) + (i * 5)));
                        else
                            AddElement(new ResetterYPDF((paragrafoDx.ToLower().Contains("<b>") ? 94 : 35) + (i * 5)));

                        if (indice == 4)
                            AddElement(new SpacePDF(21));
                        AddElement(testoDx);
                        addFiller(row, 4);
                    }
                }

                if (getNota(_text.Tables[0].AsEnumerable().Where(x => x.Field<int>("idREP_IMM_MON_Pagina") == indice).ToList()[0]).Length > 0)
                {
                    string testoNota = getNota(_text.Tables[0].AsEnumerable().Where(x => x.Field<int>("idREP_IMM_MON_Pagina") == indice).ToList()[0]);
                    IEnumerable<DataRow> rows = _text.Tables[0].AsEnumerable()
                            .Where(x => x.Field<string>("notaGraf1") != null);
                    int count = testoNota.Replace("<br>", "\t").Count(x => x == '\t');
                    //var nota = new FormattedTextAreaPDF(testoNota, 60, width*2) { AutoIncrementYWritable = false, Y = EnvironmentFacade.RendererFacade.YLowerLimit - 18 - (5 * count), FontSize = 6, FontColor = ColorPDF.Nero, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                    var nota = new FormattedTextAreaPDF(testoNota, 60, width * 2) { AutoIncrementYWritable = false, Y = EnvironmentFacade.RendererFacade.YLowerLimit - 13 - (5 * count), FontSize = 6, FontColor = ColorPDF.Nero, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify };
                    AddElement(nota);
                }
            }
        }


        protected void addFiller(DataRow row, int position)
        {
            int x = 0;
            int y = 0;
            switch (position)
            {
                case 3:
                    x = 35;
                    y = 130;
                    break;
                case 4:
                    x = 600;
                    y = 150;
                    break;
            }
            if (row.Field<string>("bytesImage") != null && row.Field<int>("isIcon") != null && row.Field<int>("isIcon") == position)
            {
                var casetta = new ImagePDF(x, 0.25F, "CASA.jpeg") { AutoIncrementYWritable = false, Y = EnvironmentFacade.RendererFacade.YLowerLimit - y };
                AddElement(casetta);
            }
        }

        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()
        {
            return null;
        }

        /// <summary>
        /// Recupera i testi
        /// </summary>
        /// <returns></returns>
        protected DataSet GetTextSet()
        {
            #region Definizione dei parametri

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

            #endregion

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

    }

    public static class StringExtensions
    {
        public static List<string> SplitAtOccurence(this string input, string separator, int occurence)
        {
            var parts = input.Split(new string[] { separator }, StringSplitOptions.RemoveEmptyEntries);
            var partlist = new List<string>();
            var result = new List<string>();
            for (int i = 0; i < parts.Length; i++)
            {
                if (partlist.Count == occurence)
                {
                    result.Add(string.Join(separator.ToString(), partlist));
                    partlist.Clear();
                }
                partlist.Add(parts[i]);
                if (i == parts.Length - 1) result.Add(string.Join(separator.ToString(), partlist)); // if no more parts, add the rest
            }
            return result;
        }
    }

}
