using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using PDFGenerator.Presentation.Section;
using PDFGenerator;
using PDFGenerator.Presentation.Section.Tables;
using PDFGenerator.Presentation.Section.Charts;
using PDFGenerator.BusinessLayer;
using PDFGenerator.BusinessLayer.DataSection;
using System.Data;
using ceTe.DynamicPDF;

namespace PDFGenerator.Presentation.Section
{
    public class FD200 : SIstogramma, ISezione
    {
        string Titolo = string.Empty;
        string _testotitolo;
        string _testointroduttivo;
        string _testoAlternativo;
        NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        public FD200()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        /// <summary>
        /// Testo introduttivo della sezione.
        /// </summary>
        public string TestoIntroduttivo
        {
            get
            {
                return _testointroduttivo;
            }
            set
            {
                _testointroduttivo = value;
            }
        }

        /// <summary>
        /// Testo del titolo della sezione.
        /// </summary>
        public string TestoTitolo
        {
            get
            {
                return _testotitolo;
            }
            set
            {
                _testotitolo = value;
            }
        }

        public string TestoAlternativo
        {
            get { return _testoAlternativo; }
            set { _testoAlternativo = value; }
        }

        public void setTitolo(string label)
        {
            Titolo = label;
        }

        public void writeSezione(DataThread dataThread)
        {
            DocumentPDF document = dataThread.DocumentPDF;
            DatiTabella datiHeaderCaratteristiche = new DatiTabella();
            DatiTabella datiAsset = new DatiTabella();
            Tabella tab = new Tabella(document.getMargineLeft(), document.getLastPos());

            DataSet set = dataThread.Data.DatiSezione;

            // Titolo della sezione
            logger.Info("Titolo della sezione FD200 " + _testointroduttivo);
            document.setLastPos(-40);
            document.setChapterHeader(string.Concat(_testointroduttivo.Replace("/$Banca$/", dataThread.NomeRete), "<br>"), 0, 520, 8);

            #region Sezione per stampare solo l'header della tabella
            logger.Info("Scrittura di solo header della tabella Titolo della seconda tabella " + _testointroduttivo);
            DataSet _ds = new DataSet();
            DataTable _dt = new DataTable();
            _dt.Columns.Add("Asset Class", typeof(System.String));
            _dt.Columns.Add("Portafoglio modello (%)", typeof(System.String));
            _dt.Columns.Add("Portafoglio attuale (%)", typeof(System.String));

            _ds.Tables.Add(_dt);
            DataRow dr = _dt.NewRow();
            dr[0] = "";
            dr[1] = "";
            dr[2] = "";

            _dt.Rows.Add(dr);

            datiHeaderCaratteristiche.table = _ds.Tables[0];

            datiHeaderCaratteristiche.setY(document.getLastPos() + 10);
            datiHeaderCaratteristiche.setX(document.getMargineLeft());

            datiHeaderCaratteristiche.setHeader(true);
            datiHeaderCaratteristiche.setCellSpace(10);
            datiHeaderCaratteristiche.setCell(150, ceTe.DynamicPDF.TextAlign.Left, Globals.OpenTypeFontVerdanaB, false);
            datiHeaderCaratteristiche.setCell(150, ceTe.DynamicPDF.TextAlign.Left, Globals.OpenTypeFontVerdanaB, false);
            datiHeaderCaratteristiche.setCell(150, ceTe.DynamicPDF.TextAlign.Left, Globals.OpenTypeFontVerdanaB, false);

            tab.ColoreDirectBankB = "green";

            document.InsertTable(tab.getTabella(datiHeaderCaratteristiche));

            ceTe.DynamicPDF.Merger.ImportedPage page1 = document.getCurrentPage();
            #endregion

            #region Grafico Portafoglio modello
            logger.Info("FD200 -  Inizio impostazione grafico Portafoglio modello");
            List<IValoriSerie> listaValoriPesoRelativo = new List<IValoriSerie>();
            foreach (var item in set.Tables["AssetClass"].AsEnumerable())
            {
                IValoriSerie IvaloriSeriePesoRelativo = new IValoriSerie();
                IvaloriSeriePesoRelativo.chiave = item[0].ToString();
                IvaloriSeriePesoRelativo.valore = Convert.ToDecimal(item[4]);
                IvaloriSeriePesoRelativo.colore = System.Drawing.Color.FromArgb((int)item["Red"], (int)item["Green"], (int)item["Blue"]);
                listaValoriPesoRelativo.Add(IvaloriSeriePesoRelativo);
            }

            ////double altezzaGraficoPesoRischio_Prodotto = 15 * (tabellaDati.Datasource.Rows.Count + 0.5);
            IstoFarfallaS133BIS graficoCaratteristiche = new IstoFarfallaS133BIS(320, 440);  //92 //85   750  //158  //200 //300
            graficoCaratteristiche.DocumentPDF = document;
            graficoCaratteristiche.PositionX = 200;  //145
            graficoCaratteristiche.PositionY = Convert.ToInt32(document.getLastPos() + 22); //32 //38 //42 //542 //22;
            graficoCaratteristiche.AxisY_LineColor = true;
            graficoCaratteristiche.AxisY_Hide = true; //false;
            graficoCaratteristiche.AxysX_Increment = Convert.ToDecimal(1);
            graficoCaratteristiche.AxisY_DashStyle = Dundas.Charting.WebControl.ChartDashStyle.DashDot;
            graficoCaratteristiche.isShadowOffset = false;    // Abilita l'ombreggiatura delle barre per ESG è fissato a 40 
            graficoCaratteristiche.isPixelPointWidth = "40"; // serve per dimensionare l'altezza delle barre
            graficoCaratteristiche.BorderLineColor = System.Drawing.Color.FromArgb(0, 0, 0);
            graficoCaratteristiche.BorderLineWidth = 10;
            SerieIstoFarfallaS133BIS seriePesoRelativo = new SerieIstoFarfallaS133BIS();

            seriePesoRelativo = new SerieIstoFarfallaS133BIS();
            seriePesoRelativo.Name = "Caratteristiche%";
            seriePesoRelativo.Values = listaValoriPesoRelativo;
            //seriePesoRelativo.ElementPosition = new Dundas.Charting.WebControl.ElementPosition(1F, -5F, 50.7F, 105F);
            seriePesoRelativo.ElementPosition = new Dundas.Charting.WebControl.ElementPosition(1F, -5F, 50.7F, 120F);  // ultimo parametro per aumentare lo spazio tra le barre
            seriePesoRelativo.AxisY_CustumizedByValues = false;
            seriePesoRelativo.ReverseAxisY = false;
            seriePesoRelativo.Axisy_Interval = 10;

            graficoCaratteristiche.SerieList.Add(seriePesoRelativo);

            logger.Info("FD200 - Inizio scrittura Portafoglio modello");
            // Disegno il grafico
            graficoCaratteristiche.Draw();  //// Pino Test 15/09/2022
            logger.Info("FD200 - Fine grafico Portafoglio modello ");
            #endregion

            #region Grafico Portafoglio Attuale
            logger.Info("FD200 -  Inizio impostazione grafico Portafoglio Attuale");
            List<IValoriSerie> listaValoriPortafoglioAttuale = new List<IValoriSerie>();
            foreach (var item in set.Tables["AssetClass"].AsEnumerable())
            {
                IValoriSerie IvaloriSeriePesoRelativo = new IValoriSerie();
                IvaloriSeriePesoRelativo.chiave = item[0].ToString();
                IvaloriSeriePesoRelativo.valore = Convert.ToDecimal(item[3]);
                IvaloriSeriePesoRelativo.colore = System.Drawing.Color.FromArgb((int)item["Red"], (int)item["Green"], (int)item["Blue"]);
                listaValoriPortafoglioAttuale.Add(IvaloriSeriePesoRelativo);
            }

            IstoFarfallaS133BIS graficoPortafoglioAttuale = new IstoFarfallaS133BIS(320, 200);  //92 //85   //750  158
            graficoPortafoglioAttuale.DocumentPDF = document;
            graficoPortafoglioAttuale.PositionX = 360;
            graficoPortafoglioAttuale.PositionY = Convert.ToInt32(document.getLastPos() + 22); //32 //38 //42 //542;
            graficoPortafoglioAttuale.AxisY_LineColor = true;
            graficoPortafoglioAttuale.AxisY_Hide = true; //false;
            graficoPortafoglioAttuale.AxysX_Increment = Convert.ToDecimal(1);
            graficoPortafoglioAttuale.AxisY_DashStyle = Dundas.Charting.WebControl.ChartDashStyle.DashDot;
            graficoPortafoglioAttuale.isShadowOffset = false;    // Abilita l'ombreggiatura delle barre per ESG è fissato a 40 
            graficoPortafoglioAttuale.isPixelPointWidth = "40"; // serve per dimensionare l'altezza delle barre
            graficoPortafoglioAttuale.BorderLineColor = System.Drawing.Color.FromArgb(0, 0, 0);
            graficoPortafoglioAttuale.BorderLineWidth = 10;
            SerieIstoFarfallaS133BIS seriePortafoglioAttuale = new SerieIstoFarfallaS133BIS();


            seriePortafoglioAttuale = new SerieIstoFarfallaS133BIS();
            seriePortafoglioAttuale.Name = "PortafoglioAttuale%";
            seriePortafoglioAttuale.Values = listaValoriPortafoglioAttuale;
            //seriePesoRelativo.ElementPosition = new Dundas.Charting.WebControl.ElementPosition(1F, -5F, 50.7F, 105F);
            seriePortafoglioAttuale.ElementPosition = new Dundas.Charting.WebControl.ElementPosition(1F, -5F, 50.7F, 120F);  // ultimo parametro per aumentare lo spazio tra le barre
            seriePortafoglioAttuale.AxisY_CustumizedByValues = false;
            seriePortafoglioAttuale.ReverseAxisY = false;
            seriePortafoglioAttuale.Axisy_Interval = 10;

            graficoPortafoglioAttuale.SerieList.Add(seriePortafoglioAttuale);

            logger.Info("FD200 - Inizio scrittura Portafoglio Attuale");
            // Disegno il grafico
            graficoPortafoglioAttuale.Draw();  //// Pino Test 15/09/2022
            logger.Info("FD200 - Fine grafico Portafoglio Attuale ");
            #endregion

            // Inserisco riga bianca per effetto distanziatore
            logger.Info("Inizio inserimento riga bianca sotto caratteristiche");
            page1.Elements.Add(new ceTe.DynamicPDF.PageElements.Rectangle(document.getMargineLeft(), document.getLastPos() + 22, 500, 6, 0, new RgbColor(255, 255, 255)));

            ceTe.DynamicPDF.Merger.ImportedPage page = document.getCurrentPage();

            page.Elements.Add(new ceTe.DynamicPDF.PageElements.Rectangle(document.getMargineLeft(), document.getLastPos() + 168, 500, 6, 0, new RgbColor(255, 255, 255)));

            #region Elenco Asset
            /****** Inserimento tabella con le due colonne e con la colonna delle Caratteristiche riempita ********/
            logger.Info("Inizio inserimento tabella Asset");
            datiAsset.table = set.Tables["AssetClass"];
            Tabella tabellaMacroAsset = new Tabella(document.getMargineLeft(), document.getLastPos() + 75, 0, -2, 0.009F);   //90  68  78 //60

            tabellaMacroAsset.Datasource = datiAsset.table;
            tabellaMacroAsset.Header = false;
            tabellaMacroAsset.DimensioneLinea = 0;
            tabellaMacroAsset.AltezzaCella = 25; //35;  //20
            tabellaMacroAsset.Colonne.Add(new Colonna("AssetClassName", "Asset Class", 150, TipoAllineamento.SINISTRA, false, 9, false, TipoColonna.TESTO));
            tabellaMacroAsset.Draw(datiAsset, document);
            logger.Info("Fine inserimento tabella Asset");
            /***********************************************************************************************************/
            #endregion
        }

        public void writeSezioneFD200(DataThread dataThread)
        {
            DocumentPDF document = dataThread.DocumentPDF;
            DatiTabella datiHeaderCaratteristiche = new DatiTabella();
            DatiTabella datiAsset = new DatiTabella();
            Tabella tab = new Tabella(document.getMargineLeft(), document.getLastPos());

            DataSet set = dataThread.Data.DatiSezione;

            tabMacroAssetClass = set.Tables["AssetClass"];

            // Titolo della sezione
            //logger.Info("Titolo della sezione FD200 " + _testointroduttivo);
            //document.setLastPos(-40);
            //document.setChapterHeader(string.Concat(_testointroduttivo.Replace("/$Banca$/", dataThread.NomeRete), "<br>"), 0, 520, 8);

            DirectBanker = "S";

            base.writeSezione200(dataThread);
        }

        public void writeSezione200New(DataThread dataThread)
        {
            DocumentPDF document = dataThread.DocumentPDF;
            DatiTabella datiHeaderCaratteristiche = new DatiTabella();
            //DatiTabella datiHeaderPercentualeAttuale = new DatiTabella();
            //DatiTabella datiMacroAsset = new DatiTabella();
            //Tabella tab = new Tabella(document.getMargineLeft(), document.getLastPos());

            DataSet set = dataThread.Data.DatiSezione;
            DataTable dati = set.Tables[0];

            // Testo del paragrafo
            logger.Info("Titolo della sezione " + _testointroduttivo);
            document.setLastPos(-40);
            document.setSezTitolo(dataThread.SezioneReport.Titolo);
            document.setChapterHeader(string.Concat(_testointroduttivo.Replace("/$Banca$/", dataThread.NomeRete), "<br>"), 0, 520, 8);

            base.DirectBanker = "S";

            #region Tabella con Grafici

            document.setLastPos(150);

            datiHeaderCaratteristiche.table = dati;
            datiHeaderCaratteristiche.setCellSpace(10);

            var tabellaAsset = new TablePDFEvolution(document.getMargineLeft(), 230, dati)
            {
                Style = Style.ConsulenzaUnica,
                Header = true,
                Footer = false,
                AlternateRow = false,
                RowHeight = 28,
                ShowSeparationLines = false,
                PageBreak = true,
                HeaderTextHorizontalAlign = HorizontalAlignmentType.Destra,
                ShowBorderHeader = true,
            };
            tabellaAsset.Columns.Add(new ColumnPDF("AssetClassName", 150, HorizontalAlignmentType.Sinistra, false, false, 7, ColumnType.Testo, "AssetClassName", "Asset class") { HeaderFontSize = 7, FontSize = 7 });
            tabellaAsset.Columns.Add(new ColumnPDF("percentuale_modello", 185, HorizontalAlignmentType.Sinistra, false, false, 7, ColumnType.Testo, "percentuale_modello", "Portafoglio modello (%)") { HeaderFontSize = 7, HeaderPaddingLeft = 0, PaddingLeft = 3, DeltaYContent = 2, FontSize = 7 }); //{ HeaderPaddingRight = 80, PaddingRight = 20, HeaderFontSize = 7, DeltaYContent = 2, FontSize = 7});
            tabellaAsset.Columns.Add(new ColumnPDF("percentuale", 185, HorizontalAlignmentType.Sinistra, false, false, 7, ColumnType.Testo, "percentuale", "Portafoglio attuale (%)") { HeaderFontSize = 7, HeaderPaddingLeft = 0, PaddingLeft = 3, DeltaYContent = 2, FontSize = 7 });


            var list = new List<double>();
            list.Add(Convert.ToDouble(dati.AsEnumerable().Max(x => x["percentuale_modello"])));
            list.Add(Convert.ToDouble(dati.AsEnumerable().Max(x => x["percentuale"])));
            list.Add(Convert.ToDouble(dati.AsEnumerable().Min(x => x["percentuale_modello"])));
            list.Add(Convert.ToDouble(dati.AsEnumerable().Min(x => x["percentuale"])));
            var max = (float)Math.Round(list.Max());
            var min = (float)Math.Round(list.Min());

            tabellaAsset.min = min;
            tabellaAsset.max = max;

            tabellaAsset.minValorePercentuale = (float)Convert.ToDouble(dati.AsEnumerable().Min(x => x["percentuale"]));
            tabellaAsset.maxValorePercentuale = (float)Convert.ToDouble(dati.AsEnumerable().Max(x => x["percentuale"]));

            tabellaAsset.minValorePercentualeModello = (float)Convert.ToDouble(dati.AsEnumerable().Min(x => x["percentuale_modello"]));
            tabellaAsset.maxValorePercentualeModello = (float)Convert.ToDouble(dati.AsEnumerable().Max(x => x["percentuale_modello"]));

            tabellaAsset.Draw(datiHeaderCaratteristiche, document);
            #endregion
        }
    }
}