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.Threading;
using System.Globalization;
using System.Collections.Generic;
using Dundas.Charting.WebControl;
using ContrattoSei.Utilities;


namespace PDFGenerator.Presentation.Section
{
    class S147 : ISezione
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        public S147() {
        }
        private string _testointroduttivo;
        private string _testointroduttivoAlternativo;

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

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

        public void writeSezione(DataThread dataThread)
        {
            DocumentPDF document = dataThread.DocumentPDF;
            //DataSectionParameter dataSectionParameter = paramSez.getParam();
            FormatNum conv = new FormatNum();
            DatiTabella datitab = new DatiTabella();

            DataSetS147 set = (DataSetS147)dataThread.Data.DatiSezione;
            ceTe.DynamicPDF.Merger.ImportedPage page = document.getCurrentPage();
            double copertura = Convert.ToDouble(set.PesiValuteTotali.Rows[0]["Copertura"]) * 100;
            //document.setHeaderSpace(40);

            int hCellTab = 23;//30--25
            int sFont = 8;
            int hBottRett = 18;//22
            int wBottRett = 258;//254
            int hBott = 10;//10
            int wBott = 40;//40

            document.setSezTitolo(dataThread.SezioneReport.Titolo.Replace("/$Banca$/", dataThread.NomeRete));
            document.setChapterHeader(dataThread.SezioneReport.TestoIntroduttivo.Replace("/$Banca$/", dataThread.NomeRete), 0, 520, 8);

            #region Tabella a destra della piramide
            // disegno la tabella a destra della piramide.
            #region datasource tabella
            //setta la datatable
            datitab.table = set.PesiValuteTotali;

            #endregion

            Tabella tabella = new Tabella();
            tabella.LineeTabella = false;
            tabella.Y = document.getLastPos();
            tabella.X = document.getMargineLeft();
            tabella.Header = true;
            tabella.SaltoPagina = false;
            tabella.AltezzaCella = hCellTab;// 30;
            tabella.Datasource = datitab.table;
            datitab.setHeaderDim(hCellTab);
            datitab.setHeaderFont(sFont);
            tabella.Colonne.Add(new Colonna("Pallino", "Valuta", 40, TipoAllineamento.SINISTRA, false, sFont, false, TipoColonna.IMMAGINE_E_TESTO));
            tabella.Colonne.Add(new Colonna("Bandiera", "", 30, TipoAllineamento.SINISTRA, false, sFont, false, TipoColonna.IMMAGINE_E_TESTO));
            tabella.Colonne.Add(new Colonna("Valuta", "", 100, TipoAllineamento.SINISTRA, false, sFont, false));
            tabella.Colonne.Add(new Colonna("Peso", "Peso %" + (copertura <100 ? " *" : ""), 80, TipoAllineamento.DESTRA, false, sFont, false));
            tabella.Draw(datitab, document);

            #region Pallini Valute e Bandierine

            float xLabelCtv = document.getMargineLeft();
            float yLabelCtv = document.getLastPos() + 40;

           

            Dictionary<string, System.Drawing.Color> colori = this.getColorCurrencies();
            System.Drawing.Color colore;
            string pathImage = @UtilityManager.getAppSetting("pathGraf") + @"\Flags\";
            
            int numSimboli = 21;
            //float yPallino = 0;
            float yPallino = tabella.Y + 7 + numSimboli;
            foreach (DataRow drSimbolo in set.PesiValuteTotali.Rows)
            {
                try
                {
                    if (drSimbolo["VALUTA"].ToString().ToUpper() == "EUR")
                    {
                        colore = colori[drSimbolo["VALUTA"].ToString().ToUpper()];
                    }
                    else
                    {
                        colore = colori["ALTRE"];
                    }
                }
                catch (Exception e)
                {
                    logger.Error(String.Concat("colori", e.Message, dataThread.CodiceFiscale, dataThread.Rete));
                    colore = colori["ALTRE"];
                }

                RgbColor theColor = new RgbColor(colore.R, colore.G, colore.B);

                ceTe.DynamicPDF.PageElements.Circle simboloAI = new ceTe.DynamicPDF.PageElements.Circle(document.getMargineLeft() + 2, yPallino - 5, 8 / 1.414F, theColor, theColor);
                page.Elements.Add(simboloAI);
                try
                {
                    page.Elements.Add(new ceTe.DynamicPDF.PageElements.Image(pathImage + drSimbolo["VALUTA"].ToString().ToUpper() + ".png", document.getMargineLeft() + 25, yPallino - 10, 0.41F));
                }
                catch (Exception e)
                {
                    logger.Error(String.Concat(e.Message, "1", dataThread.CodiceFiscale, dataThread.Rete));
                }
                yPallino += hCellTab;
            }

            #endregion

            #endregion tabella a destra della piramide

            if (copertura< 100)
                page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("(*) Grado di copertura: " + conv.ConvertNum(copertura) + "%", document.getMargineLeft(), yPallino, 180, 10, Globals.OpenTypeFontVerdana, 7));

            document.setLastPos(0);

            #region Grafico a Farfalla

            #region Recupero i valori da assegnare alle serie del grafico

            List<IValoriSerie> listaValoriPesoNegativo = new List<IValoriSerie>();
            List<IValoriSerie> listaValoriPesoPositivo = new List<IValoriSerie>();

            bool presenzaValoriNegativi = false;

            foreach (DataRow row in set.PesiValuteNegative.Rows)
            {
                IValoriSerie IvaloriSeriePesoNegativo = new IValoriSerie();
                IvaloriSeriePesoNegativo.chiave = row["VALUTA"].ToString();
                IvaloriSeriePesoNegativo.valore = Convert.ToDecimal(row["Peso"]);
                if (IvaloriSeriePesoNegativo.valore > 0)
                    presenzaValoriNegativi = true;
                System.Drawing.Color c = colori["ALTRE"];
                try
                {
                    if (IvaloriSeriePesoNegativo.chiave == "EUR")
                    {
                        c = colori[IvaloriSeriePesoNegativo.chiave];
                    }
                    //else
                    //{
                    //    colore = colori["ALTRE"];
                    //}

                    //c = colori[IvaloriSeriePesoNegativo.chiave];
                }
                catch (Exception e)
                {
                    logger.Error(String.Concat(e.Message, " ", IvaloriSeriePesoNegativo.chiave));
                }
                IvaloriSeriePesoNegativo.colore = c;//System.Drawing.Color.FromArgb(Convert.ToInt32(row["Red"]), Convert.ToInt32(row["Green"]), Convert.ToInt32(row["Blue"]));
                listaValoriPesoNegativo.Add(IvaloriSeriePesoNegativo);
            }

            double maxValue = 0;

            foreach (DataRow row in set.PesiValutePositive.Rows)
            {
                IValoriSerie IvaloriSeriePesoPositivo = new IValoriSerie();
                IvaloriSeriePesoPositivo.chiave = row["VALUTA"].ToString();
                IvaloriSeriePesoPositivo.valore = Convert.ToDecimal(row["Peso"]);

                if (Convert.ToDouble(IvaloriSeriePesoPositivo.valore) > maxValue)
                    maxValue = Convert.ToDouble(IvaloriSeriePesoPositivo.valore);

                System.Drawing.Color c = colori["ALTRE"];
                try
                {
                    //c = colori[IvaloriSeriePesoPositivo.chiave];
                    if (IvaloriSeriePesoPositivo.chiave == "EUR")
                    {
                        c = colori[IvaloriSeriePesoPositivo.chiave];
                    }
                }
                catch (Exception e)
                {
                    logger.Error(String.Concat(e.Message, " ", IvaloriSeriePesoPositivo.chiave, dataThread.CodiceFiscale, dataThread.Rete));
                }
                IvaloriSeriePesoPositivo.colore = c;//System.Drawing.Color.FromArgb(Convert.ToInt32(row["Red"]), Convert.ToInt32(row["Green"]), Convert.ToInt32(row["Blue"]));
                listaValoriPesoPositivo.Add(IvaloriSeriePesoPositivo);
            }

            #endregion
            

            //double altezzaGraficoPesoRischio_Prodotto = 31 * (tabella.Datasource.Rows.Count + 0.5);
            double altezzaGraficoPesoRischio_Prodotto = 24 * (tabella.Datasource.Rows.Count + 0.5);
            //double altezzaGraficoPesoRischio_Prodotto = 180;
            double larghezzaGrafico = 500;

            if (presenzaValoriNegativi)
                larghezzaGrafico = 250;


            IstoFarfallaS110 graficoPesoRischio_Prodotto = graficoPesoRischio_Prodotto = new IstoFarfallaS110(larghezzaGrafico, altezzaGraficoPesoRischio_Prodotto);
            graficoPesoRischio_Prodotto.DocumentPDF = document;
            graficoPesoRischio_Prodotto.PositionX = 290;
            graficoPesoRischio_Prodotto.PositionY = Convert.ToInt32(tabella.Y + 15);//17
            //graficoPesoRischio_Prodotto.AxisY_LineColor = false;
            graficoPesoRischio_Prodotto.AxisY_Hide = false;
            graficoPesoRischio_Prodotto.AxysX_Increment = Convert.ToDecimal(0.5);

            SerieIstoFarfallaS110 seriePesoNegativo = new SerieIstoFarfallaS110();
            if (presenzaValoriNegativi)
            {

                seriePesoNegativo.Name = "PesoNegativo";
                seriePesoNegativo.Values = listaValoriPesoNegativo;
                seriePesoNegativo.ElementPosition = new Dundas.Charting.WebControl.ElementPosition(1F, -2F, 50.7F, 105F);
                seriePesoNegativo.ReverseAxisY = true;
                seriePesoNegativo.ShowLabelAsValue = false;
                seriePesoNegativo.AxisY_MaximumValue = 100;
                seriePesoNegativo.Axisy_Interval = 20;
            }

            SerieIstoFarfallaS110 seriePesoPositivo = new SerieIstoFarfallaS110();
            seriePesoPositivo.Name = "PesoPositivo";
            seriePesoPositivo.Values = listaValoriPesoPositivo;
            if (presenzaValoriNegativi)
                seriePesoPositivo.ElementPosition = new Dundas.Charting.WebControl.ElementPosition(49.3F, -2, 50.7F, 105F);
            else
                seriePesoPositivo.ElementPosition = new Dundas.Charting.WebControl.ElementPosition(1F, -2, 50.7F, 105F);
            seriePesoPositivo.Axisy_Interval = 20;
            seriePesoPositivo.AxisY_MaximumValue = 100; // maxValue + 10 > 100 ? maxValue : maxValue + 10;        
            seriePesoPositivo.ShowLabelAsValue = false;

            if (presenzaValoriNegativi)
                graficoPesoRischio_Prodotto.SerieList.Add(seriePesoNegativo);
            graficoPesoRischio_Prodotto.SerieList.Add(seriePesoPositivo);

            // Disegno il grafico
            graficoPesoRischio_Prodotto.Draw();

            //rettangolo giusto 
            page.Elements.Add(new ceTe.DynamicPDF.PageElements.Rectangle(290.5F, (float)(tabella.Y + altezzaGraficoPesoRischio_Prodotto), wBottRett, hBottRett, RgbColor.LightGrey, RgbColor.LightGrey));

            float passo = 23.5F;

            //label negative
            if (presenzaValoriNegativi)
                for (int i = -1; i >= -5; --i)
                    page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label((seriePesoNegativo.Axisy_Interval * i).ToString(), 407.5F + (passo * i), (float)(tabella.Y + altezzaGraficoPesoRischio_Prodotto), wBott, hBott, Globals.OpenTypeFontVerdana, sFont, ceTe.DynamicPDF.TextAlign.Left, ceTe.DynamicPDF.RgbColor.Black));

            if (presenzaValoriNegativi)
                page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("0", 414.5F, (float)(tabella.Y + altezzaGraficoPesoRischio_Prodotto), wBott, hBott, Globals.OpenTypeFontVerdana, sFont, ceTe.DynamicPDF.TextAlign.Left, ceTe.DynamicPDF.RgbColor.Black));
            else
            {
                page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("0", 294.5F, (float)(tabella.Y + altezzaGraficoPesoRischio_Prodotto), wBott, hBott, Globals.OpenTypeFontVerdana, sFont, ceTe.DynamicPDF.TextAlign.Left, ceTe.DynamicPDF.RgbColor.Black));
                passo *= 2;
            }
            //label positive
            for (int i = 1; i <= 5; ++i)
                if (presenzaValoriNegativi)
                    page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label((seriePesoPositivo.Axisy_Interval * i).ToString(), 414.5F + (passo * i), (float)(tabella.Y + altezzaGraficoPesoRischio_Prodotto),wBott , hBott, Globals.OpenTypeFontVerdana, sFont, ceTe.DynamicPDF.TextAlign.Left, ceTe.DynamicPDF.RgbColor.Black));
                else
                    page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label((seriePesoPositivo.Axisy_Interval * i).ToString(), 294.5F + (passo * i), (float)(tabella.Y + altezzaGraficoPesoRischio_Prodotto), wBott, hBott, Globals.OpenTypeFontVerdana, sFont, ceTe.DynamicPDF.TextAlign.Left, ceTe.DynamicPDF.RgbColor.Black));

            #endregion
        }


        private Dictionary<string, System.Drawing.Color> getColorCurrencies()
        {
            Dictionary<string, System.Drawing.Color> colori = new Dictionary<string, System.Drawing.Color>();
            colori.Add("EUR", System.Drawing.Color.FromArgb(217, 81, 33));
            //colori.Add("USD", System.Drawing.Color.FromArgb(82, 135, 197));
            //colori.Add("CHF", System.Drawing.Color.FromArgb(255, 200, 0));
            //colori.Add("GBP", System.Drawing.Color.FromArgb(255, 0, 255));
            //colori.Add("CNY", System.Drawing.Color.FromArgb(255, 0, 0));
            //colori.Add("JPY", System.Drawing.Color.FromArgb(0, 0, 0));
            colori.Add("ALTRE", System.Drawing.Color.FromArgb(131, 188, 180));

 

            return colori;

        }
    }

}