using System;
using Consulenza.ReportWriter.Business;
using Consulenza.ReportWriter.Business.OBJ_PDF;
using System.Data;
using Consulenza.ReportCommon;
using Consulenza.ReportWriter.Business.CHART_PDF;
using Consulenza.ReportWriter.Business.Entity;
using System.Collections.Generic;
using System.Linq;
 
namespace Consulenza.ReportWriter.Manager.Section.Unica
{
    /// <summary>
    /// S50.ContributoRischioAssetClass idSezione = 93
    /// </summary>
    public class S50 : Entity.Section
    {
        public S50(EnvironmentFacade environmentFacade, int idSection)
            : base(environmentFacade, idSection)
        {
            try
            {
                Draw();
            }
            catch (Exception ex)
            {
                SectionLogger.Write("S50", ex.Message, SectionLoggerMessageLevel.E, EnvironmentFacade.ReportEnvironment);
            }
        }

        protected override sealed void Draw()
        {
            var dati = GetDataSet();
           
            #region ASSET

            var dtTabella = new DataTable();
            dtTabella.Columns.Add(new DataColumn("Oggetto", typeof(string)));
            dtTabella.Columns.Add(new DataColumn("Asset", typeof(string)));
            dtTabella.Columns.Add(new DataColumn("Controvalore", typeof(string)));
            dtTabella.Columns.Add(new DataColumn("VaR", typeof(string)));
            // dtTabella.Columns.Add(new DataColumn("Pesorelativo", typeof(string)));
            dtTabella.Columns.Add(new DataColumn("Pesorelativo", typeof(string)));
            //dtTabella.Columns.Add(new DataColumn("spazio", typeof(string)));

            dtTabella.Columns.Add(new DataColumn("Rischiorelativo", typeof(string)));
            //dtTabella.Columns.Add(new DataColumn("Rischiorelativo", typeof(string)));

            foreach (DataRow r in dati.Tables["asset"].Rows)
            {
                if ((decimal)r["Rischiorelativo"] == 0M)
                {
                    r["Rischiorelativo"] = 0.001M;
                }
                dtTabella.Rows.Add(
                    "",
                    r["Asset"].ToString(),
                    Helper.FormatCurrency(r["Controvaloreattuale"].ToString()),
                    Helper.FormatCurrency(r["VaR"].ToString()),
                    r["Pesorelativo"],
                    r["Rischiorelativo"]);
            }
            dtTabella.Rows.Add(//riga vuota per spazio al footer
                   "",
                   "",
                   "",
                   "",
                  "0",
                "0");
            var tabellaAsset = new TablePDF(EnvironmentFacade.RendererFacade.XLeftLimit, dtTabella, dati.Tables["assetfooter"])
            {
                Style = Style.ConsulenzaUnica,
                Header = true,

                AlternateRow = false,
                RowHeight = 21,
                //AutoIncrementYWritable = false,
                ShowSeparationLines = false,
                Footer = true,
                HeaderTextHorizontalAlign = HorizontalAlignmentType.Sinistra,
                HeaderHeight = 27,
                FooterYOffset = -10
            };


            var list = new List<double>();
            list.Add(Convert.ToDouble(dati.Tables["asset"].AsEnumerable().Max(x => x["Pesorelativo"])));
            list.Add(Convert.ToDouble(dati.Tables["asset"].AsEnumerable().Max(x => x["Rischiorelativo"])));
            var valoreMassimo = (float)Helper.Round(list.Max());


            tabellaAsset.Columns.Add(new ColumnPDF("oggetto", 15, HorizontalAlignmentType.Sinistra, false, false, 7, ColumnType.Objectpdf, "oggetto", string.Empty) { DeltaYContent = 10, FontSize = 7 });
            tabellaAsset.Columns.Add(new ColumnPDF("descrizione", 115, HorizontalAlignmentType.Sinistra, false, false, 7, ColumnType.Testo, "Asset", "Asset class") { HeaderFontSize = 7, PaddingLeft = 5, DeltaYContent = 3, FontSize = 7 });
            tabellaAsset.Columns.Add(new ColumnPDF("contro", 70, HorizontalAlignmentType.Sinistra, false, false, 7, ColumnType.Testo, "Controvalore", "Controvalore<br>attuale (€)") { HeaderFontSize = 7, PaddingRight = 4, DeltaYContent = 3, FontSize = 7 });
            tabellaAsset.Columns.Add(new ColumnPDF("var", 50, HorizontalAlignmentType.Sinistra, false, false, 7, ColumnType.Testo, "VaR", "VaR (%)") { HeaderFontSize = 7, HeaderPaddingLeft = 10, DeltaYContent = 3, FontSize = 7 });

            tabellaAsset.Columns.Add(new ColumnPDF("pesoobj", 135, HorizontalAlignmentType.Destra, false, false, 7, ColumnType.Objectpdf, "Pesorelativo", "Peso relativo (%)") { HeaderFontSize = 7, FontSize = 7, DeltaYContent = 8, HeaderPaddingRight = 20 });
            tabellaAsset.Columns.Add(new ColumnPDF("rischioobj", 135, HorizontalAlignmentType.Sinistra, false, false, 7, ColumnType.Objectpdf, "Rischiorelativo", "Rischio relativo (%)") { HeaderFontSize = 7, FontSize = 7, DeltaYContent = 8, PaddingLeft = 10, HeaderPaddingLeft = 10 });

            tabellaAsset.FooterColumns.Add(new ColumnPDF("Asset", 130, HorizontalAlignmentType.Sinistra, true, true, 7, ColumnType.Testo) { FontSize = 7 });
            tabellaAsset.FooterColumns.Add(new ColumnPDF("ControvaloreAttuale", 70, HorizontalAlignmentType.Destra, true, true, 7, ColumnType.Decimale) { PaddingRight = 4, FontSize = 7 });
            tabellaAsset.FooterColumns.Add(new ColumnPDF("VaR", 50, HorizontalAlignmentType.Destra, true, true, 7, ColumnType.Testo) { FontSize = 7 });

            float larghezzaBarra = 0;
            float larghezzaSpazioTestoPercentuale = 0;
            float larghezzaMinimaSpazioTestoPercentuale = 35;
            float deltaXBarra = 0;

            int i = 0;
            foreach (DataRow ro in dati.Tables["asset"].Rows)
            {
                var colore = ro["Asset"].ToString() == "" ? ColorPDF.Bianco : new ColorPDF(Convert.ToInt32(ro["Red"]), Convert.ToInt32(ro["Green"]), Convert.ToInt32(ro["Blue"]));
                tabellaAsset.Cells[0, i].ValueObject = new CirclePDF(11, 11, colore);
                //tabellaAsset.Cells[6, i].Value = " ";
                #region peso relativo
                larghezzaBarra = Helper.GetWidthProportional((float)Convert.ToDecimal(ro["Pesorelativo"]), valoreMassimo, tabellaAsset.Columns[4].Width - 50);
                larghezzaSpazioTestoPercentuale = tabellaAsset.Columns[4].Width - larghezzaBarra;
                deltaXBarra = -larghezzaBarra - 10;
                if (larghezzaSpazioTestoPercentuale < larghezzaMinimaSpazioTestoPercentuale)
                {
                    deltaXBarra = -(tabellaAsset.Columns[4].Width - larghezzaMinimaSpazioTestoPercentuale);
                    larghezzaSpazioTestoPercentuale = larghezzaMinimaSpazioTestoPercentuale;
                }
                tabellaAsset.Cells[4, i].HorizontalAlignment = HorizontalAlignmentType.Destra;
                if ((Math.Round(Convert.ToDecimal(ro["Pesorelativo"]),2)) == 0)
                {
                    ro["Pesorelativo"] = 0.001m.ToString();
                    colore = ColorPDF.Bianco;
                }
                tabellaAsset.Cells[4, i].ValueObjectList = new List<Business.Entity.ObjectPDF>()
                        {
                            new RectanglePDF(13, larghezzaBarra , colore),
                            new FormattedTextAreaPDF(   Helper.FormatDecimal(Convert.ToDecimal(ro["Pesorelativo"]).ToString(), 2),
                                                        0, larghezzaSpazioTestoPercentuale)
                            {
                                DeltaY = 2,
                                TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Right,
                                DeltaX = deltaXBarra,
                                FontSize = 7
                            }
                        };

                #endregion

                #region barra colonna RischioRelativo

                larghezzaBarra = Helper.GetWidthProportional((float)Convert.ToDecimal(ro["Rischiorelativo"]), valoreMassimo, tabellaAsset.Columns[5].Width - 50);
                larghezzaSpazioTestoPercentuale = tabellaAsset.Columns[5].Width - larghezzaBarra;
                deltaXBarra = larghezzaBarra + 10;
                if (larghezzaSpazioTestoPercentuale < larghezzaMinimaSpazioTestoPercentuale)
                {
                    deltaXBarra = (tabellaAsset.Columns[5].Width - larghezzaMinimaSpazioTestoPercentuale);
                    larghezzaSpazioTestoPercentuale = larghezzaMinimaSpazioTestoPercentuale;
                }
                if (ro["VaR"].ToString() == "n.c.")
                {
                    tabellaAsset.Cells[5, i].ValueObjectList = new List<Business.Entity.ObjectPDF>()
                            {
                                new RectanglePDF(12, 1, ColorPDF.Bianco),
                                new FormattedTextAreaPDF( "n.c.",                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
                                                        0, 
                                                        30 ) 
                                {                                 
                                DeltaY = 2,
                                TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Left,
                                DeltaX = deltaXBarra,
                                FontSize = 7
                                }   
                            };
                }
                else if (Math.Round(Convert.ToDecimal(ro["Rischiorelativo"]),2) != 0)
                {
                    tabellaAsset.Cells[5, i].ValueObjectList = new List<Business.Entity.ObjectPDF>()
                        {
                            new RectanglePDF(12, larghezzaBarra, colore),
                            new FormattedTextAreaPDF(   Helper.FormatDecimal(Convert.ToDecimal(ro["Rischiorelativo"]).ToString(), 2),
                                                        0,
                                                        larghezzaSpazioTestoPercentuale)
                            {
                                DeltaY = 2,
                                TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Left,
                                DeltaX = deltaXBarra,
                                FontSize = 7
                            }
                        };
                }
                else
                {
                    ro["Rischiorelativo"] = 0.001m.ToString();
                    colore = ColorPDF.Bianco;
                    tabellaAsset.Cells[5, i].ValueObjectList = new List<Business.Entity.ObjectPDF>()
                        {
                            new RectanglePDF(12, larghezzaBarra, colore),
                            new FormattedTextAreaPDF(   Helper.FormatDecimal(Convert.ToDecimal(ro["Rischiorelativo"]).ToString(), 2),
                                                        0,
                                                        larghezzaSpazioTestoPercentuale)
                            {
                                DeltaY = 2,
                                TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Left,
                                DeltaX = deltaXBarra,
                                FontSize = 7
                            }
                        };
                }
                #endregion
                tabellaAsset.Cells[2, i].HorizontalAlignment =
                tabellaAsset.Cells[3, i].HorizontalAlignment = HorizontalAlignmentType.Destra;
                i++;
            }
            int b = 0;
            foreach (DataRow fo in dati.Tables["assetfooter"].Rows)
            {
                if (fo["Colonna1"].ToString() == "Totale non rappresentabile" ||
                    fo["Colonna1"].ToString() == "Patrimonio non rappresentabile")
                {
                    tabellaAsset.FooterCells[0, b].BackgroundColor =
                    tabellaAsset.FooterCells[1, b].BackgroundColor =
                    tabellaAsset.FooterCells[2, b].BackgroundColor = ColorPDF.Bianco;
                    tabellaAsset.FooterCells[0, b].FontBold =
                    tabellaAsset.FooterCells[1, b].FontBold =
                    tabellaAsset.FooterCells[2, b].FontBold = false;

                }
                b++;
            }

            #endregion            
            AddElement(tabellaAsset);
            AddElement(new SpacePDF(10));

            if (GetNota().Length > 0)
            {
                AddElement(new SpacePDF(15));
                tabellaAsset.Notes.Add(
                    new TableNotePDF(TableNotePDF.TableNotePositionType.PièDiTabella,
                        GetNota(),
                        new[] { "compl" },
                        "",
                        TableNotePDF.TableNoteAsteriskPositionType.PieDiTabella) { FontSize = 6, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify }
                        );
            }
         
        }

        protected sealed override DataTable GetDataTable()
        {
            return null;
        }

        protected sealed override DataSet GetDataSet()
        {

            var ds = new DataSet();
            ds.Tables.Add(new DataTable("asset"));
            ds.Tables.Add(new DataTable("assetfooter"));

            var rischioRelativoDistAsset = datiSeiUnico.rischioUnit().rischio.rischioRelativoDistAsset;
            var assetDisplayInfos = datiSeiUnico.displayInfos().assetDisplayInfos;
            var pianificazioneVerticale = datiSeiUnico.pianificazioneUnit().pianificazioneVerticale;


            ds.Tables["asset"].Columns.Add(new DataColumn("Asset", typeof(string)));
            ds.Tables["asset"].Columns.Add(new DataColumn("Red", typeof(int)));
            ds.Tables["asset"].Columns.Add(new DataColumn("Green", typeof(int)));
            ds.Tables["asset"].Columns.Add(new DataColumn("Blue", typeof(int)));
            ds.Tables["asset"].Columns.Add(new DataColumn("Controvaloreattuale", typeof(decimal)));
            ds.Tables["asset"].Columns.Add(new DataColumn("Var", typeof(string)));
            ds.Tables["asset"].Columns.Add(new DataColumn("Pesorelativo", typeof(decimal)));
            ds.Tables["asset"].Columns.Add(new DataColumn("Rischiorelativo", typeof(decimal)));
            foreach (var item in from c in assetDisplayInfos
                                 join l in rischioRelativoDistAsset.classes on c.key equals l.id
                                 orderby c.value.order //descending
                                 select new
                                 {
                                     l.name,
                                     l.var,
                                     l.currentEquivalent,
                                     l.relativeWeight,
                                     l.relativeRisk,
                                     new ColorPDF(c.value.fill).Red,
                                     new ColorPDF(c.value.fill).Green,
                                     new ColorPDF(c.value.fill).Blue
                                 })
            {
                ds.Tables["asset"].Rows.Add(
                    item.name,
                    item.Red,
                    item.Green,
                    item.Blue,
                    item.currentEquivalent,//controvalore
                    item.var,//var
                    item.relativeWeight,//pesorelativo
                    item.relativeRisk//rischiorelativo
                );

            }

            ds.Tables["assetfooter"].Columns.Add(new DataColumn("Colonna1", typeof(string)));
            ds.Tables["assetfooter"].Columns.Add(new DataColumn("Colonna2", typeof(decimal)));
            ds.Tables["assetfooter"].Columns.Add(new DataColumn("VaR", typeof(string)));
            if (rischioRelativoDistAsset.others != null)
            {
                if (rischioRelativoDistAsset.others.currentEquivalent != 0)
                {
                    ds.Tables["assetfooter"].Rows.Add(
                        "Patrimonio rappresentabile",
                        rischioRelativoDistAsset.financialResources.currentEquivalent,
                        rischioRelativoDistAsset.financialResources.var
                    );
                    ds.Tables["assetfooter"].Rows.Add(
                        "Patrimonio non rappresentabile",
                        rischioRelativoDistAsset.others.currentEquivalent,
                        rischioRelativoDistAsset.others.var
                    );
                }
            }
            ds.Tables["assetfooter"].Rows.Add(
                string.Format("Patrimonio {0}", Helper.ReplaceVariables("$/Banca/$", EnvironmentFacade.ReportEnvironment)),
                rischioRelativoDistAsset.total.currentEquivalent,
                GetNota().Length > 0 ? rischioRelativoDistAsset.total.var + "*" : rischioRelativoDistAsset.total.var
             );


            return ds;
        }

        public virtual string GetNota()
        {
            string nota = "";
            var gradoCopertura = datiSeiUnico.rischioUnit().rischio.rischioRelativoDistAsset.total.coverage;
            if (gradoCopertura > 0 && gradoCopertura < 100)
            {
                nota += string.Format("Grado di copertura prodotti in termini di Rischio Mercato  (VaR): {0}", Helper.FormatDecimal(gradoCopertura.ToString(), 2));
            }
            return nota;
        }
    }
}
