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 PDFGenerator.Presentation.Section.Tables;
using PDFGenerator.BusinessLayer.DataSection;
using PDFGenerator.BusinessLayer;
using System.Resources;
using System.Reflection;
using ContrattoSei.Utilities;

namespace PDFGenerator.Presentation.Section
{
    class S95 : ISezione  
    {
          private string _header = "";

        public string Header
        {
            get { return _header; }
            set { _header = value; }
        }

        private TipoReport _tipologiaReport ;
        public TipoReport TipologiaReport
        {
            get { return _tipologiaReport; }
            set { _tipologiaReport = value; }
        }

        private string _testoIntroduttivo = string.Empty;
        public string TestoIntroduttivo
        {
            get { return _testoIntroduttivo; }
            set { _testoIntroduttivo = value; }
        }

        private string _testoChiusura = string.Empty;
        public string TestoChiusura
        {
            get { return _testoChiusura; }
            set { _testoChiusura = value; }
        }
        
        
        public S95() {
            //
            // TODO: Add constructor logic here
            //
        }

        #region ISezione Members

        public void writeSezione(DataThread dataThread) {

            DocumentPDF document = dataThread.DocumentPDF;
            DataSetS95 set = (DataSetS95)dataThread.Data.DatiSezione;

            if (dataThread.TipoReport.ToUpper() == "DIAGNOSI")
                document.setSezTitoloDiagnosi(dataThread.SezioneReport.Titolo);
            else
                document.setSezTitolo(dataThread.SezioneReport.Titolo);
            string tempTesto = dataThread.SezioneReport.TestoIntroduttivo;
            
            if (dataThread.Rete.ToUpper() == "S")
                tempTesto = tempTesto.Replace("Fideuram", "Sanpaolo Invest");

            document.setChapterHeader(tempTesto);

            //if (dataThread.TipoReport.ToUpper() == "MONITORAGGIO")
            //{
            //    document.writeText(document.getMargineLeft() + 55, document.getLastPos() - 15, "•  al Rischio Mercato del patrimonio complessivo", 9, 450, ceTe.DynamicPDF.TextAlign.Left);
            //    document.writeText(document.getMargineLeft() + 55, document.getLastPos(), "•  al Rischio Credito del patrimonio complessivo", 9, 450, ceTe.DynamicPDF.TextAlign.Left);
            //    //document.setLastPos(document.getLastPos() + 18);
            //    document.setHeaderSpace(40);
            //}
           


            # region profilofinanziario
            DatiTabella profilofinanziarioDatiTab = new DatiTabella();
            profilofinanziarioDatiTab.table = set.Tables["Profilofinanziario"];
            profilofinanziarioDatiTab.setIsLinee(1);
            profilofinanziarioDatiTab.setCell(210, ceTe.DynamicPDF.TextAlign.Left, Globals.OpenTypeFontVerdanaB, true);
            profilofinanziarioDatiTab.setCell(273, ceTe.DynamicPDF.TextAlign.Left, Globals.OpenTypeFontVerdana, false);
            profilofinanziarioDatiTab.setX(document.getMargineLeft());
            Tabella profilofinanziarioTab = new Tabella();
            if (dataThread.TipoReport.ToUpper() == "DIAGNOSI") profilofinanziarioTab.HeaderFont = 8;
            profilofinanziarioTab.LineaFineTabella = true;
            //profilofinanziarioTab.
            # endregion

            # region ProfiloRischio
            DatiTabella datitab = new DatiTabella();
            datitab.table = set.Tables["ProfiloRischio"];
            datitab.setIsLinee(1);
            datitab.setCell(165, ceTe.DynamicPDF.TextAlign.Left, Globals.OpenTypeFontVerdanaB, true);
            datitab.setCell(273, ceTe.DynamicPDF.TextAlign.Left, Globals.OpenTypeFontVerdana, false);
            datitab.setX(document.getMargineLeft() + 45);
            Tabella tab = new Tabella();
            if (dataThread.TipoReport.ToUpper() == "DIAGNOSI") tab.HeaderFont = 8;
            tab.LineaFineTabella = true;
            # endregion

            # region ProfiloDate
            DatiTabella ProfiloDateDatiTab = new DatiTabella();
            ProfiloDateDatiTab.table = set.Tables["ProfiloDate"];
            ProfiloDateDatiTab.setIsLinee(1);
            ProfiloDateDatiTab.setCell(210, ceTe.DynamicPDF.TextAlign.Left, Globals.OpenTypeFontVerdanaB, true);
            ProfiloDateDatiTab.setCell(273, ceTe.DynamicPDF.TextAlign.Left, Globals.OpenTypeFontVerdana, false);
            ProfiloDateDatiTab.setX(document.getMargineLeft());
            Tabella ProfiloDateTab = new Tabella();
            if (dataThread.TipoReport.ToUpper() == "DIAGNOSI") ProfiloDateTab.HeaderFont = 8;
            ProfiloDateTab.LineaFineTabella = true;
            # endregion

            profilofinanziarioDatiTab.setY(document.getLastPos());
            document.InsertTable(profilofinanziarioTab.getTabella(profilofinanziarioDatiTab));

            float ydatitab = document.getLastPos() + profilofinanziarioDatiTab.getNumRow() * profilofinanziarioDatiTab.GetRowDim();
            datitab.setY(ydatitab);
            
            float yProfiloDateDatiTab = ydatitab + (datitab.getNumRow()-1) * datitab.GetRowDim() ;
            ProfiloDateDatiTab.setY(yProfiloDateDatiTab);

            //float yFooter = yProfiloDateDatiTab + ProfiloDateDatiTab.getNumRow() * ProfiloDateDatiTab.GetRowDim() ;
            float yFooter = ProfiloDateDatiTab.GetRowDim() * 4;
            ceTe.DynamicPDF.Merger.ImportedPage page = document.getCurrentPage();

            string relativePath = UtilityManager.getAppSetting("Slider");
            System.Reflection.Assembly thisExe;
            thisExe = System.Reflection.Assembly.GetExecutingAssembly();
            System.IO.Stream fileSlider = thisExe.GetManifestResourceStream(relativePath);
            page.Elements.Add(new ceTe.DynamicPDF.PageElements.Image(fileSlider, 57 + 150 + 85 + 25, document.getLastPos() + datitab.GetRowDim() * 0.7F, 0.25F));
           

            
            //datitab.setY(document.getLastPos());
            relativePath = UtilityManager.getAppSetting("SliderRischioCredito");
            System.IO.Stream fileRischioCreditoSlider = thisExe.GetManifestResourceStream(relativePath);
            page.Elements.Add(new ceTe.DynamicPDF.PageElements.Image(fileRischioCreditoSlider, 57 + 150 + 85 + 25, document.getLastPos() + datitab.GetRowDim() * 0.7F + datitab.GetRowDim(), 0.25F));
            relativePath = UtilityManager.getAppSetting("MarkerLarge");
            System.IO.Stream fileMarker = thisExe.GetManifestResourceStream(relativePath);

            float VaRMassimo = Convert.ToSingle(datitab.table.Rows[0]["Valore"]);
            float xMarker = getX(VaRMassimo.ToString());
            float yMarker = document.getLastPos() + datitab.GetRowDim() * 0.7F;

            decimal totalePartiteViaggianti = dataThread.PartiteViaggiantiInvestimento + dataThread.PartiteViaggiantiDisinvestimento;            
            FormatNum conv = new FormatNum();
            //IMPORTANT
            //V When doing S95 Remove from here and make the right value into the DSS95 

            datitab.table.Rows[0]["Valore"] = conv.ConvertNum(Convert.ToDouble(datitab.table.Rows[0]["Valore"])) + "%";


            if (dataThread.ReportType().TipoReport == TipoReport.MONITORAGGIO)
            {
                string note = string.Empty;
                note = getExperinceLevel(datitab.table.Rows[2]["Valore"].ToString(), dataThread.NomeRete);
                
                datitab.table.Rows[2].Delete();
                document.InsertTable(tab.getTabella(datitab));            

                document.InsertTable(ProfiloDateTab.getTabella(ProfiloDateDatiTab));
                
                if (dataThread.TotalNegativeCurrentAccountValue >= 0 && totalePartiteViaggianti == 0)
                {
                    #region TOTALE PATRIMONIO
                    page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(string.Format(Resource.S95_NotaOperazioniInCorsZero, dataThread.NomeRete), ProfiloDateDatiTab.getX(), document.getLastPos() + ProfiloDateDatiTab.GetRowDim() * 4, 500F, 30F, Globals.OpenTypeFontVerdana, 8));

                    DatiTabella totalitab = new DatiTabella();
                    totalitab.table = set.Tables["Totali"];

                    Tabella tabellaTotale = new Tabella(document.getMargineLeft(), document.getLastPos() + ProfiloDateDatiTab.GetRowDim() * 7);
                    if (dataThread.TipoReport.ToUpper() == "DIAGNOSI") tabellaTotale.HeaderFont = 8;
                    tabellaTotale.SaltoPagina = false;
                    tabellaTotale.Header = false;

                    tabellaTotale.Colonne.Add(new Colonna("Descrizione", "", 130, TipoAllineamento.SINISTRA, true, 9, true));
                    tabellaTotale.Colonne.Add(new Colonna("Controvalore", "", 150, TipoAllineamento.DESTRA, true, 9, true));

                    tabellaTotale.Draw(totalitab, document);

                    document.setSezFooter(string.Format(Resource.S95_Monitoring_Note, dataThread.NomeRete) + " " + note, ProfiloDateDatiTab.GetRowDim() * 6 + totalitab.GetRowDim(), 0, 9);

                    #endregion
                }
                else if (dataThread.TotalNegativeCurrentAccountValue < 0 && totalePartiteViaggianti == 0)
                {
                    page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(string.Format(Resource.S95_NotaOperazioniInCorsoZero_CCNegativo, dataThread.NomeRete), ProfiloDateDatiTab.getX(), document.getLastPos() + ProfiloDateDatiTab.GetRowDim() * 4, 500F, 30F, Globals.OpenTypeFontVerdana, 8));
                    page.Elements.Add(new ceTe.DynamicPDF.PageElements.Line(document.getMargineLeft() - 5, document.getLastPos() + ProfiloDateDatiTab.GetRowDim() * 4 + 30, document.getMargineLeft() + 285, document.getLastPos() + ProfiloDateDatiTab.GetRowDim() * 4 + 30, 2F, new RgbColor(232, 236, 237)));

                    DatiTabella ctvdatitab = new DatiTabella();
                    ctvdatitab.table = set.Tables["Dati"];

                    Tabella tabellaDati = new Tabella(document.getMargineLeft(), document.getLastPos() + ProfiloDateDatiTab.GetRowDim() * 7);
                    if (dataThread.TipoReport.ToUpper() == "DIAGNOSI") tabellaDati.HeaderFont = 8;
                    tabellaDati.DimensioneLinea = 2;

                    tabellaDati.Colonne.Add(new Colonna("Descrizione", "", 130, TipoAllineamento.SINISTRA, false, 8, false));
                    tabellaDati.Colonne.Add(new Colonna("Controvalore", "", 150, TipoAllineamento.DESTRA, false, 8, false));

                    tabellaDati.Draw(ctvdatitab, document);

                    DatiTabella totalitab = new DatiTabella();
                    totalitab.table = set.Tables["Totali"];

                    Tabella tabellaTotale = new Tabella(document.getMargineLeft(), document.getLastPos() + ProfiloDateDatiTab.GetRowDim() * 7 + datitab.GetRowDim() * 2);
                    if (dataThread.TipoReport.ToUpper() == "DIAGNOSI") tabellaTotale.HeaderFont = 8;
                    tabellaTotale.Colonne.Add(new Colonna("Descrizione", "", 130, TipoAllineamento.SINISTRA, true, 9, true));
                    tabellaTotale.Colonne.Add(new Colonna("Controvalore", "", 150, TipoAllineamento.DESTRA, true, 9, true));

                    tabellaTotale.Draw(totalitab, document);

                    document.setSezFooter(string.Format(Resource.S95_Monitoring_Note, dataThread.NomeRete) + " " + note, ProfiloDateDatiTab.GetRowDim() * 6 + datitab.GetRowDim() * 2 + totalitab.GetRowDim(), 0, 9);
                }
                else if (dataThread.TotalNegativeCurrentAccountValue < 0 && totalePartiteViaggianti != 0)
                {
                    page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(string.Format(Resource.S95_NotaOperazioniInCorsoNotZero_CCNegativo, dataThread.NomeRete), ProfiloDateDatiTab.getX(), document.getLastPos() + ProfiloDateDatiTab.GetRowDim() * 4, 500F, 30F, Globals.OpenTypeFontVerdana, 8));
                    page.Elements.Add(new ceTe.DynamicPDF.PageElements.Line(document.getMargineLeft() - 5, document.getLastPos() + ProfiloDateDatiTab.GetRowDim() * 4 + 30, document.getMargineLeft() + 285, document.getLastPos() + ProfiloDateDatiTab.GetRowDim() * 4 + 30, 2F, new RgbColor(232, 236, 237)));

                    DatiTabella ctvdatitab = new DatiTabella();
                    ctvdatitab.table = set.Tables["Dati"];

                    Tabella tabellaDati = new Tabella(document.getMargineLeft(), document.getLastPos() + ProfiloDateDatiTab.GetRowDim() * 7);
                    if (dataThread.TipoReport.ToUpper() == "DIAGNOSI") tabellaDati.HeaderFont = 8;
                    tabellaDati.DimensioneLinea = 2;

                    tabellaDati.Colonne.Add(new Colonna("Descrizione", "", 130, TipoAllineamento.SINISTRA, false, 9, false));
                    tabellaDati.Colonne.Add(new Colonna("Controvalore", "", 150, TipoAllineamento.DESTRA, false, 9, false));

                    tabellaDati.Draw(ctvdatitab, document);

                    DatiTabella totalitab = new DatiTabella();
                    totalitab.table = set.Tables["Totali"];

                    Tabella tabellaTotale = new Tabella(document.getMargineLeft(), document.getLastPos() + ProfiloDateDatiTab.GetRowDim() * 7 + datitab.GetRowDim() * 3);
                    if (dataThread.TipoReport.ToUpper() == "DIAGNOSI") tabellaTotale.HeaderFont = 8;
                    tabellaTotale.Colonne.Add(new Colonna("Descrizione", "", 130, TipoAllineamento.SINISTRA, true, 9, true));
                    tabellaTotale.Colonne.Add(new Colonna("Controvalore", "", 150, TipoAllineamento.DESTRA, true, 9, true));

                    tabellaTotale.Draw(totalitab, document);

                    document.setSezFooter(string.Format(Resource.S95_Monitoring_Note, dataThread.NomeRete) + " " + note, ProfiloDateDatiTab.GetRowDim() * 6 + datitab.GetRowDim() * 3 + totalitab.GetRowDim(), 0, 9);
                }
                else if (dataThread.TotalNegativeCurrentAccountValue == 0 && totalePartiteViaggianti != 0)
                {
                    page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(string.Format(Resource.S95_NotaOperazioniInCorsoNotZero_CCNegativo, dataThread.NomeRete), ProfiloDateDatiTab.getX(), document.getLastPos() + ProfiloDateDatiTab.GetRowDim() * 4, 500F, 30F, Globals.OpenTypeFontVerdana, 8));
                    page.Elements.Add(new ceTe.DynamicPDF.PageElements.Line(document.getMargineLeft() - 5, document.getLastPos() + ProfiloDateDatiTab.GetRowDim() * 4 + 30, document.getMargineLeft() + 285, document.getLastPos() + ProfiloDateDatiTab.GetRowDim() * 4 + 30, 2F, new RgbColor(232, 236, 237)));

                    DatiTabella ctvdatitab = new DatiTabella();
                    ctvdatitab.table = set.Tables["Dati"];

                    Tabella tabellaDati = new Tabella(document.getMargineLeft(), document.getLastPos() + ProfiloDateDatiTab.GetRowDim() * 7);
                    if (dataThread.TipoReport.ToUpper() == "DIAGNOSI") tabellaDati.HeaderFont = 8;
                    tabellaDati.DimensioneLinea = 2;

                    tabellaDati.Colonne.Add(new Colonna("Descrizione", "", 130, TipoAllineamento.SINISTRA, false, 9, false));
                    tabellaDati.Colonne.Add(new Colonna("Controvalore", "", 150, TipoAllineamento.DESTRA, false, 9, false));

                    tabellaDati.Draw(ctvdatitab, document);

                    DatiTabella totalitab = new DatiTabella();
                    totalitab.table = set.Tables["Totali"];

                    Tabella tabellaTotale = new Tabella(document.getMargineLeft(), document.getLastPos() + ProfiloDateDatiTab.GetRowDim() * 7 + datitab.GetRowDim() * 2);
                    if (dataThread.TipoReport.ToUpper() == "DIAGNOSI") tabellaTotale.HeaderFont = 8;
                    tabellaTotale.Colonne.Add(new Colonna("Descrizione", "", 130, TipoAllineamento.SINISTRA, true, 9, true));
                    tabellaTotale.Colonne.Add(new Colonna("Controvalore", "", 150, TipoAllineamento.DESTRA, true, 9, true));

                    tabellaTotale.Draw(totalitab, document);

                    //string S95_Monitoring_Note = "{0} effettua inoltre una verifica sulla complessità degli strumenti finanziari da Lei detenuti.\r\nSulla base delle indicazioni da Lei fornite nel questionario di profilatura,";
                     string S95_Monitoring_Note = "{0} effettua inoltre una verifica sulla complessità degli strumenti finanziari da lei detenuti.\r\nSulla base delle informazioni da lei fornite nel questionario di profilatura,"; 


                    document.setSezFooter(string.Format(S95_Monitoring_Note, dataThread.NomeRete) + " " + note, ProfiloDateDatiTab.GetRowDim() * 6 + datitab.GetRowDim() * 2 + totalitab.GetRowDim(), 0, 9);
                }
                
            }
            else
            {
                datitab.table.Rows[2].Delete();
                document.InsertTable(tab.getTabella(datitab));
                
                document.InsertTable(ProfiloDateTab.getTabella(ProfiloDateDatiTab));

            }

            page.Elements.Add(new ceTe.DynamicPDF.PageElements.Image(fileMarker, xMarker, yMarker , 0.25F));

            //aggiorno il puntatore alla posizione da cui si puٍ scrivere
            document.setLastPos(yFooter);
        }

        #endregion

        /// <summary>
        /// Ritorna la x sulla quale andrà posizionato il marker (barra nera) in funzione del VaR massimo del profilo.
        /// Il posizionamento della x in questa sezione è fisso e non graduale.
        /// La funzione è valida per le fasce di profilo 1.5 , 3.5 , 7.5 , 12 , 23
        /// </summary>
        /// <param name="varmassimo">var massimo del profilo</param>
        /// <returns></returns>
        private float getX(string varmassimo) {
            float xPartenza = 292;
            if (varmassimo == SoglieVar.sVar1) return xPartenza + 7 + 25;
            if (varmassimo == SoglieVar.sVar2) return xPartenza + 21 + 25;
            if (varmassimo == SoglieVar.sVar3) return xPartenza + 42 + 25;
            if (varmassimo == SoglieVar.sVar4) return xPartenza + 70 + 25;
            if (varmassimo == SoglieVar.sVar5) return xPartenza + 107 + 25;
            return xPartenza;            
        }

        /// <summary>
        /// Return the Experince Level depending on the passed value 
        /// <Owner> Marian Zaki</Owner>
        /// <Date> 04052010 </Date>
        /// </summary>
        /// <param name="experinceLevel">
        ///     case 1: low
        ///     case 2: medium
        ///     case 3: high
        /// </param>
        /// <returns> The footer note depend on the experince level </returns>
        private  string getExperinceLevel(string experinceLevel, string reteName)
        {
            int experinceLevelValue;
            string experinceLevelName = string.Empty;
            if (int.TryParse(experinceLevel, out experinceLevelValue))
            {

                string S95_Monitoring_Note_ExperinceLevel_Low = "{0} ritiene adeguati al suo profilo finanziario tutti gli strumenti finanziari aventi complessità bassa. Ritiene invece non adeguati strumenti aventi complessità media o alta.";
                string S95_Monitoring_Note_ExperinceLevel_Medium =	"{0} ritiene adeguati al suo profilo finanziario tutti gli strumenti finanziari aventi complessità bassa o media. Ritiene invece non adeguati strumenti aventi complessità alta."	;
                string S95_Monitoring_Note_ExperinceLevel_High	= "{0} ritiene adeguati al suo profilo finanziario tutti gli strumenti finanziari presenti nel suo portafoglio."	;


                switch (experinceLevel)
                {
                    case "1":
                        //experinceLevelName = Resource.S95_Monitoring_Note_ExperinceLevel_Low;
                        experinceLevelName = string.Format(S95_Monitoring_Note_ExperinceLevel_Low, reteName);
                        break;
                    case "2":
                        //experinceLevelName = Resource.S95_Monitoring_Note_ExperinceLevel_Medium;
                        experinceLevelName = string.Format(S95_Monitoring_Note_ExperinceLevel_Medium, reteName);
                        break;
                    case "3":
                        //experinceLevelName = Resource.S95_Monitoring_Note_ExperinceLevel_High;
                        experinceLevelName = string.Format(S95_Monitoring_Note_ExperinceLevel_High, reteName);
                        break;
                    default:
                        experinceLevelName = string.Empty;
                        break;

                }

                return experinceLevelName;
            }
            else
                return string.Empty;
        }
    }
}