using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using ceTe.DynamicPDF;
using ceTe.DynamicPDF.Text;
using Dundas.Charting.WebControl;
using PDFGenerator.Presentation.Section.Tables;
using PDFGenerator.BusinessLayer.DataSection;
using PDFGenerator.Presentation.Section.Charts;
using PDFGenerator.BusinessLayer;
using ContrattoSei.Utilities;

namespace PDFGenerator.Presentation.Section
{
    public class S42 : ISezione
    {
        string Titolo = string.Empty;
        private string _testointroduttivo;
        private string _testotitolo;



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

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



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



        /// <summary>
        /// Stampa la sezione
        /// </summary>
        /// <param name="paramSez"></param>
        public void writeSezione(DataThread dataThread)
        {
            DocumentPDF document = dataThread.DocumentPDF;

           // float xLab = 122;
            //float xImg = 170;
            float xLine = 50;
            float widthMacroAsset = 120;
            float widthLine = 320;
            float widthRectangleTable = widthLine - xLine + 3;
            //float InLab = 13;
            float fontSize = 9;
            float heightLabel = 11;
           // float yDistanceHeaderLabel = 19;
           // float yDistanceVar = 23;

            float altezzaRettangolo = 58;

            int altezzaGrafico = 160;
            float altezzaGraficoMenoEtichette = altezzaGrafico - 40;



            DatiTabella datitab = new DatiTabella();
            DataSetS42 set = (DataSetS42)dataThread.Data.DatiSezione;

            //calcola se entra nella pagina altrimenti aggiunge una nuova pagina.
            if (document.checkMargin(175 + altezzaGrafico))
                document.addPage();

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

            #region Titolo e testo introduttivo
            if (dataThread.TipoReport.ToUpper() == "DIAGNOSI")
                document.setSezTitoloDiagnosi(_testotitolo);
            else
                document.setSezTitolo(_testotitolo);
            document.setSezHeader(_testointroduttivo);
            document.setHeaderSpace(25);

            #endregion

            double var1 = 0;
            if (set.RischioPatrimonioFinanziario.Rows.Count != 0)
                var1 = Convert.ToDouble((decimal)set.RischioPatrimonioFinanziario.Rows[0]["Var"]);

            #region Tabella sotto al grafico
            //datitab.table = set.Tables["RischioDiversificazione"];
            // MZ: Use the RischioDiversificazioneTable instead of RischioDiversificazione to allow to have VAR as string in case of coverage is null.
            datitab.table = set.Tables["RischioDiversificazioneTable"];
            datitab.setIsLinee(1);
            datitab.setHeader();
            datitab.setCell(152, ceTe.DynamicPDF.TextAlign.Left, Globals.OpenTypeFontVerdana, false);
            datitab.setCell(100, ceTe.DynamicPDF.TextAlign.Right, Globals.OpenTypeFontVerdana, false);
            datitab.setCell(140, ceTe.DynamicPDF.TextAlign.Right, Globals.OpenTypeFontVerdana, false);
            datitab.setCell(120, ceTe.DynamicPDF.TextAlign.Right, Globals.OpenTypeFontVerdana, false);


            datitab.setY(document.getLastPos() + altezzaGrafico + 10);
            datitab.setX(document.getMargineLeft());
            datitab.setIsRet();
            datitab.setCellSpace(0);
            Tabella tab = new Tabella();
            document.InsertTable(tab.getTabella(datitab));

            datitab.table = set.Tables["RischioDiversificazione"];
            //
            //Tabella tabellaRischioDiversificazione = new Tabella();
            //tabellaRischioDiversificazione.X = document.getMargineLeft();
            //tabellaRischioDiversificazione.Y = document.getLastPos() + altezzaGrafico + 10;
            //tabellaRischioDiversificazione.Header = true;
            //tabellaRischioDiversificazione.Datasource = datitab.table;

            //tabellaRischioDiversificazione.Colonne.Add(new Colonna("Patrimonio", "Patrimonio", 152, TipoAllineamento.SINISTRA, false, 7, false));
            //tabellaRischioDiversificazione.Colonne.Add(new Colonna("Var", "Rischio<BR>(VaR %)", 80, TipoAllineamento.DESTRA, false, 7, false));
            //tabellaRischioDiversificazione.Colonne.Add(new Colonna("Diversificazione", "Diversificazione %", 140, TipoAllineamento.DESTRA, false, 7, false));
            //tabellaRischioDiversificazione.Colonne.Add(new Colonna("Copertura", "Copertura %", 140, TipoAllineamento.DESTRA, false, 7, false));


            //tabellaRischioDiversificazione.Draw(datitab, document);
            //pkthis.writeMarker(document, datitab);


            #endregion

            float dim = datitab.GetRowDim() * datitab.getNumRow();

            #region Grafico

            DatiGrafico dati = new DatiGrafico();
            dati.dataTab = datitab.table;
            //rimuovo le colonne non utili per il grafico          
            dati.dataTab.Columns.Remove(dati.dataTab.Columns["Copertura"]);
            dati.setHeight(altezzaGrafico);
            dati.setWidth(250);
            Pallini pall = new Pallini();
            Chart grafico = pall.getGrafico(dati);

            double vaRMassimo = pall.AxisY_Maximum;
            document.InsertGrafico(grafico, document.getMargineLeft() + 110, document.getLastPos() - 5);

            #endregion

            dim += (altezzaGrafico + 40);

            #region Marcatore alla sinistra del grafico

            ceTe.DynamicPDF.PageElements.Rectangle rect;
            FormatNum conv = new FormatNum();
            float yImg = document.getLastPos() - 5;

            if (set.RischioPatrimonioFinanziario.Rows.Count != 0)
            {
                //string var1 = conv.ConvertNum(set.RischioPatrimonioFinanziario.Rows[0]["Var"]);
                if (var1 > vaRMassimo)
                    var1 = vaRMassimo;
                float intervallo = (altezzaGraficoMenoEtichette / (float)vaRMassimo);
                altezzaGraficoMenoEtichette = altezzaGraficoMenoEtichette - Convert.ToSingle(0.23 * var1);

                float yRettangoloFreccia = yImg - (altezzaRettangolo / 2) + altezzaGraficoMenoEtichette - ((float)var1 * intervallo);

                page.Elements.Add(
                    new ceTe.DynamicPDF.PageElements.Rectangle(
                        document.getMargineLeft() + 5
                        , yRettangoloFreccia
                        , widthMacroAsset - 35
                        , altezzaRettangolo
                        , 0
                        , new RgbColor(232, 236, 237)
                        )
                );
                rect = new ceTe.DynamicPDF.PageElements.Rectangle(
                    document.getMargineLeft() + widthMacroAsset - 30
                    , yRettangoloFreccia
                    , altezzaRettangolo / 1.414F
                    , altezzaRettangolo / 1.414F
                    , 0
                    , new RgbColor(232, 236, 237));
                rect.Angle = 45;
                page.Elements.Add(rect);
                page.Elements.Add(
                    new ceTe.DynamicPDF.PageElements.Label("Profilo finanziario:"
                        , document.getMargineLeft() + 10
                        , yRettangoloFreccia + 2
                        , widthMacroAsset + 70
                        , heightLabel
                        , Globals.OpenTypeFontVerdana
                        , fontSize));


                string profilo = " ";

                switch (MarkPosition((float)var1))
                {
                    case 0:
                        profilo = "Prudente";
                        break;
                    case 1:
                        profilo = "Moderato";
                        break;
                    case 2:
                        profilo = "Equilibrato";
                        break;
                    case 3:
                        profilo = "Dinamico";
                        break;
                    case 4:
                        profilo = "Aggressivo";
                        break;
                    default:
                        break;
                }


                page.Elements.Add(
                    new ceTe.DynamicPDF.PageElements.Label(profilo + " (" + (MarkPosition((float)var1) + 1).ToString() + ")"
                        , document.getMargineLeft() + 10
                        , yRettangoloFreccia + 23
                        , widthMacroAsset + 70
                        , heightLabel
                        , Globals.OpenTypeFontVerdana
                        , fontSize));
                page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("(VaR " + conv.ConvertNum(set.RischioPatrimonioFinanziario.Rows[0]["Var"]) + "%)"
                    , document.getMargineLeft() + 10
                    , yRettangoloFreccia + 44
                    , widthMacroAsset + 70
                    , heightLabel
                    , Globals.OpenTypeFontVerdana
                    , fontSize));
            }

            #endregion

            #region Legenda alla destra del Grafico

            string relativePath = UtilityManager.getAppSetting("LegendaDiversificazioneLarge");
            System.Reflection.Assembly thisExe;
            thisExe = System.Reflection.Assembly.GetExecutingAssembly();
            System.IO.Stream file = thisExe.GetManifestResourceStream(relativePath);
            page.Elements.Add(new ceTe.DynamicPDF.PageElements.Image(file, document.getMargineLeft() + 370, document.getLastPos() + 85, 0.50F));


            #endregion

            // setto la posizione aggiornata
            document.setLastPos(dim);

        }

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

        private int MarkPosition(float var)
        {
            int index = 0;

            if (var < Convert.ToDouble(BusinessLayer.SoglieVar.sVar1))
                index = 0;
            if ((Convert.ToDouble(BusinessLayer.SoglieVar.sVar1) < var) && (var <= Convert.ToDouble(BusinessLayer.SoglieVar.sVar2)))
                index = 1;
            if ((Convert.ToDouble(BusinessLayer.SoglieVar.sVar2) < var) && (var <= Convert.ToDouble(BusinessLayer.SoglieVar.sVar3)))
                index = 2;
            if ((Convert.ToDouble(BusinessLayer.SoglieVar.sVar3) < var) && (var <= Convert.ToDouble(BusinessLayer.SoglieVar.sVar4)))
                index = 3;
            if ((Convert.ToDouble(BusinessLayer.SoglieVar.sVar4) < var))
                index = 4;

            return index;
        }

        /// <summary>
        /// Disegna il simbolo accanto alla descrizione del patrimonio nella colonna Patrimonio.
        /// </summary>
        /// <param name="document"></param>
        /// <param name="datasource"></param>
        private void writeMarker(DocumentPDF document, DatiTabella datasource)
        {
            ceTe.DynamicPDF.Merger.ImportedPage page = document.getCurrentPage();
            float y = datasource.GetRowDim();
            float yTabella = datasource.getY();
            ceTe.DynamicPDF.PageElements.Rectangle rect;

            foreach (DataRow myRow in datasource.table.Rows)
            {
                switch (myRow["Patrimonio"].ToString().Trim().ToLower())
                {

                    //EN 27-01-2016: case "patrimonio banca fideuram":
                    case "patrimonio fideuram":
                    case "patrimonio sanpaolo invest":
                    case "patrimonio san paolo invest":
                    case "patrimonio attuale":
                        //Marker 1
                        rect = new ceTe.DynamicPDF.PageElements.Rectangle(document.getMargineLeft(), yTabella - 5 + y, 10 / 1.414F, 10 / 1.414F, 0, new RgbColor(0, 0, 0));
                        rect.Angle = 45;
                        page.Elements.Add(rect);
                        y += datasource.GetRowDim();
                        break;

                    case "patrimonio complessivo":
                        //Marker 2
                        rect = new ceTe.DynamicPDF.PageElements.Rectangle(document.getMargineLeft() - 4, yTabella - 4 + y, 8, 8, 0, new RgbColor(0, 0, 0));
                        //rect.CornerRadius = 5;
                        page.Elements.Add(rect);
                        y += datasource.GetRowDim();
                        break;

                    case "patrimonio altri istituti":
                    case "patrimonio prospettico":
                        //Marker 3
                        rect = new ceTe.DynamicPDF.PageElements.Rectangle(document.getMargineLeft() - 5, yTabella - 5 + y, 10, 10, 0, new RgbColor(0, 0, 0));
                        rect.CornerRadius = 5;
                        page.Elements.Add(rect);
                        y += datasource.GetRowDim();
                        break;

                    default:
                        break;
                }
            }
        }



    }
}