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 PDFGenerator.BusinessLayer.DataSection;
using PDFGenerator.BusinessLayer;
using System.Collections.Generic;

namespace PDFGenerator.BusinessLayer.DataSection
{
    class DSS148DistribuzioneAssetClass: IDataSection
    {
        private StructColor toBeFound = new StructColor();

        public DSS148DistribuzioneAssetClass()
        {
        }

        //#region IDataSection Members
       
        //public DataSectionResult getDataSection_old(List<SessionStruct> tabelleSessione, string querySql, DataThread dataThread)
        //{
        //    try
        //    {
        //        FormatNum num = new FormatNum();
        //        DataSectionResult dsr = new DataSectionResult();
        //        FormatNum conv = new FormatNum();
        //        String banca = dataThread.NomeRete;

        //        toBeFound.Tipo = "AssetClass";

        //        DataSetS148 ds148 = new DataSetS148();
        //       // DataSetS148.MacroAssetClassRow AssetClassRow;

        //        DataTable dt = null;
        //        decimal Totale = dataThread.PatrimonioBancaFideuramCtvAlNettoContoCorrente;
        //        decimal TotPerc = 100;
        //        dt = SectionManager.GetDataSection(tabelleSessione, querySql, dataThread); ;


        //        for (int r = 0; r < dt.Rows.Count; r++)  {
        //            DataRow dr = ds148.MacroAssetClass.NewRow();
        //            String AssetClassId = dt.Rows[r]["AssetClassId"].ToString();                   
        //            dr["Descrizione"] = dt.Rows[r]["AssetClassName"].ToString();
        //            //dr["Controvalore"] = Convert.ToDecimal(dt.Rows[r]["Controvalore"]);

        //            dr["Controvalore"] = Decimal.Round(Convert.ToDecimal(dt.Rows[r]["Controvalore"]), 2, MidpointRounding.AwayFromZero);
        //            Totale -= decimal.Parse(dr["Controvalore"].ToString());
                    
        //            dr["Percentuale"] = Decimal.Round(Convert.ToDecimal(dt.Rows[r]["Percentuale"]), 2, MidpointRounding.AwayFromZero);
        //            TotPerc -= decimal.Parse(dr["Percentuale"].ToString());
                    
        //            toBeFound.Codice = AssetClassId;
        //            int foundIdx = ClsFunzioniGeneriche.findRightColors(toBeFound);
                    
        //            dr["Red"] = ClsFunzioniGeneriche.Colors[foundIdx].Red;
        //            dr["Green"] = ClsFunzioniGeneriche.Colors[foundIdx].Green;
        //            dr["Blue"] = ClsFunzioniGeneriche.Colors[foundIdx].Blue;
        //            ds148.MacroAssetClass.Rows.Add(dr);
        //        }

        //        if (ds148.MacroAssetClass.Rows.Count > 0)  {
        //            ds148.MacroAssetClass.Rows[dt.Rows.Count - 1]["Percentuale"] = decimal.Parse(ds148.MacroAssetClass.Rows[dt.Rows.Count - 1]["Percentuale"].ToString()) + TotPerc;
        //            ds148.MacroAssetClass.Rows[dt.Rows.Count - 1]["Controvalore"] = decimal.Parse(ds148.MacroAssetClass.Rows[dt.Rows.Count - 1]["Controvalore"].ToString()) + Totale;
        //        }
        //        DataRow drtot = ds148.MacroAssetTotale.NewRow();
        //        drtot["Totale"] = "Patrimonio " + banca;
        //        drtot["Controvalore"] = num.ConvertNum(dataThread.PatrimonioBancaFideuramCtvAlNettoContoCorrente);
        //        drtot["Percentuale"] = num.ConvertNum(100);
        //        ds148.MacroAssetTotale.Rows.Add(drtot);

        //        dsr.DatiSezione = ds148;
        //        dsr.Esito = ds148.MacroAssetClass.Rows.Count;
        //        return dsr;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //}
        //#endregion

        #region IDataSection Members
      

        public DataSectionResult getDataSection(List<SessionStruct> tabelleSessione, string querySql, DataThread dataThread)
        {

            try
            {
                DataSectionResult dsr = new DataSectionResult();

                Decimal ctvTotale = 0;

                DataTable dt = SectionManager.GetDataSection(tabelleSessione, querySql, dataThread);

                DataSetS148 ds148 = new DataSetS148();
                DataRow dr;

                toBeFound.Tipo = "AssetClass";
                ds148.MacroAssetClass.Columns["Controvalore"].Caption = "Controvalore <br> (€) &nbsp; &nbsp; &nbsp; &nbsp;";
                ds148.MacroAssetClass.Columns["Percentuale"].Caption = "Peso <br> (%)";

                decimal patrimonioBancaFideuramCTV = 0;
                decimal cc = 0;
                string banca = string.Empty;
                decimal totalePartiteViaggianti = 0;

                //V
                decimal residuo = dataThread.TotaleS57;
                if (dataThread.ContoCorrente < 0)
                    residuo -= dataThread.ContoCorrente;

                DataRow tuplaMaggiore = null;
                decimal controValoreMaggiore = 0;
                DataRow tuplaPercMaggiore = null;
                decimal percMaggiore = 0;
                decimal residuoPerc = 100;
                //
                foreach (DataRow row in dt.Rows)
                {
                    dr = ds148.MacroAssetClass.NewRow();
                    dr["Descrizione"] = row["assetclassname"];
                    //V
                    decimal temp = Convert.ToDecimal(row["Controvalore"]);
                    dr["Controvalore"] = temp.ToString();
                    if (temp > controValoreMaggiore)
                    {
                        controValoreMaggiore = temp;
                        tuplaMaggiore = dr;
                    }
                    residuo -= temp;

                    decimal tempPerc = Convert.ToDecimal(row["Percentuale"]);
                    tempPerc = decimal.Round(tempPerc, 2);
                    dr["Percentuale"] = tempPerc.ToString();
                    if (tempPerc > percMaggiore)
                    {
                        percMaggiore = tempPerc;
                        tuplaPercMaggiore = dr;
                    }
                    residuoPerc -= tempPerc;
                    //
                    if (patrimonioBancaFideuramCTV == 0)
                        patrimonioBancaFideuramCTV = dataThread.Patrimoniobancafideuramctv;
                    toBeFound.Codice = row["AssetClassId"].ToString();
                    if (cc == 0)
                        cc = dataThread.ContoCorrente;
                    if (banca == string.Empty)
                        banca = (string)row["banca"];
                    if (totalePartiteViaggianti == 0)
                        totalePartiteViaggianti = dataThread.PartiteViaggiantiInvestimento + dataThread.PartiteViaggiantiDisinvestimento;
                    int foundIdx = ClsFunzioniGeneriche.findRightColors(toBeFound);

                    dr["Red"] = ClsFunzioniGeneriche.Colors[foundIdx].Red;
                    dr["Green"] = ClsFunzioniGeneriche.Colors[foundIdx].Green;
                    dr["Blue"] = ClsFunzioniGeneriche.Colors[foundIdx].Blue;

                    ctvTotale += (Decimal)row["Controvalore"];
                    ds148.MacroAssetClass.Rows.Add(dr);
                }
                //V
                ctvTotale += residuo;

                if (residuo != 0 && tuplaMaggiore != null)
                {
                    decimal temp = Convert.ToDecimal(tuplaMaggiore["Controvalore"]);
                    temp += residuo;
                    tuplaMaggiore["Controvalore"] = temp.ToString();
                }

                if (residuoPerc != 0 && tuplaPercMaggiore != null)
                {
                    decimal temp = Convert.ToDecimal(tuplaPercMaggiore["Percentuale"]);
                    temp += residuoPerc;
                    tuplaPercMaggiore["Percentuale"] = temp.ToString();
                }

                //
                DataSetS148.PatrimonioNonRappresentabileRow drPatrimonioNonRappresentabile;
                drPatrimonioNonRappresentabile = ds148.PatrimonioNonRappresentabile.NewPatrimonioNonRappresentabileRow();
                drPatrimonioNonRappresentabile.Descrizione = Resource.PatrimonioNonRappresentabile_label;
                //"Patrimonio non rappresentabile";

                //Arrotondamento i totali vengono presi da query differenti e avolte c'è la differenza di un decimale
                Decimal ctvNonRappr = dataThread.PatrimonioNonRappresentabile;
                if (ctvNonRappr <= 0)
                {
                    drPatrimonioNonRappresentabile.ControValore = 0;
                    ctvNonRappr = 0;
                }
                else
                {
                    drPatrimonioNonRappresentabile.ControValore = ctvNonRappr;
                    ds148.PatrimonioNonRappresentabile.Rows.Add(drPatrimonioNonRappresentabile);
                }

                DataSetS148.ContoCorrenteBancaFideuramRow drContoCorrenteBancaFideuramRow;
                drContoCorrenteBancaFideuramRow = ds148.ContoCorrenteBancaFideuram.NewContoCorrenteBancaFideuramRow();
                drContoCorrenteBancaFideuramRow.Descrizione = "C/C a saldo negativo";
                drContoCorrenteBancaFideuramRow.ControValore = cc;
                if (drContoCorrenteBancaFideuramRow.ControValore < 0)
                    ds148.ContoCorrenteBancaFideuram.Rows.Add(drContoCorrenteBancaFideuramRow);


                DataSetS148.ContoCorrenteBancaFideuramRow drLineaSelfRow;
                drLineaSelfRow = ds148.ContoCorrenteBancaFideuram.NewContoCorrenteBancaFideuramRow();
                drLineaSelfRow.Descrizione = "Liquidità negativa \"Linee GP Eligo\"";
                drLineaSelfRow.ControValore = dataThread.TotalSelfNegCurrentAccountValue;
                if (dataThread.TotalSelfNegCurrentAccountValue < 0)
                    ds148.ContoCorrenteBancaFideuram.Rows.Add(drLineaSelfRow);

                DataSetS148.PartiteViaggiantiRow drPartiteViaggiantiRow;
                drPartiteViaggiantiRow = ds148.PartiteViaggianti.NewPartiteViaggiantiRow();
                drPartiteViaggiantiRow.Descrizione = Resource.PartiteViaggianti;
                //"Investimenti in corso";
                drPartiteViaggiantiRow.ControValore = totalePartiteViaggianti;
                if (drPartiteViaggiantiRow.ControValore > 0)
                    ds148.PartiteViaggianti.Rows.Add(drPartiteViaggiantiRow);

                bool totalePresente = true;
                string totRappr = "TOTALE RAPPRESENTATO";
                if (drContoCorrenteBancaFideuramRow.ControValore >= 0 
                    && drPartiteViaggiantiRow.ControValore <= 0
                    && drLineaSelfRow.ControValore >= 0
                    && ctvNonRappr == 0)
                {
                    totalePresente = false;
                    totRappr = "TOTALE";
                }

                DataRow drTot = ds148.MacroAssetTotale.NewRow();
                drTot["Totale"] = totRappr;
                drTot["Controvalore"] = ctvTotale;
                drTot["Percentuale"] = 100.00;
                ds148.MacroAssetTotale.Rows.Add(drTot);


                if (totalePresente)
                {
                    DataSetS148.TotaleRow drTotale;
                    drTotale = ds148.Totale.NewTotaleRow();
                    drTotale.Descrizione = "TOTALE";
                    //modifica luca 11/09/08
                    //i dati in caso di cc positivo sono già comprensivi del c/c quindi non va sommato di nuovo
                    //drTotale.ControValore = (ctvTotale + drPatrimonioNonRappresentabile.ControValore + drContoCorrenteBancaFideuramRow.ControValore);
                    drTotale.ControValore = (ctvTotale + ctvNonRappr);
                    if (drContoCorrenteBancaFideuramRow.ControValore < 0)
                        drTotale.ControValore += drContoCorrenteBancaFideuramRow.ControValore;
                    if (drLineaSelfRow.ControValore < 0)
                        drTotale.ControValore += drLineaSelfRow.ControValore;
                    //fine modifica luca 11/09/08
                    drTotale.ControValore += totalePartiteViaggianti;
                    ds148.Totale.Rows.Add(drTotale);
                }



                #region Risorse Percentuali
                Decimal valorePrecentuale = 0;

                DataSetS148.RisorsePercentualiRow rowRisorsePercentuali = ds148.RisorsePercentuali.NewRisorsePercentualiRow();

                if (patrimonioBancaFideuramCTV == 0)
                    rowRisorsePercentuali.ValorePercentuale = 0;
                else
                {
                    valorePrecentuale = (ctvTotale / patrimonioBancaFideuramCTV) * 100;
                    rowRisorsePercentuali.ValorePercentuale = System.Math.Round(valorePrecentuale, 2, MidpointRounding.ToEven);
                }

                ds148.RisorsePercentuali.AddRisorsePercentualiRow(rowRisorsePercentuali);
                #endregion
                //Normalizzo le percentuali
                FormatNum conv = new FormatNum();
                if (dt.Rows.Count != 0)
                    conv.NormalizePerc(ds148.MacroAssetClass, "Percentuale");
                //========================================================

                dsr.DatiSezione = ds148;
                dsr.Esito = dt.Rows.Count;
                if (ctvTotale == 0)
                    dsr.Esito = 0;

                return dsr;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion


    }
}