using System;
using System.Web;
//using System.Web.Services;
//using System.Web.Services.Protocols;
using System.Text;
using System.Data;

using System.Collections;
using System.Configuration;
using PDFGenerator.BusinessLayer.DataSection;
using PDFGenerator.BusinessLayer;
using System.Collections.Generic;
using PDFGenerator;

public class DSS57ConfrontoPiramidi : IDataSection
{

   // private DataRow tuplaMaggiore = null;
    

    #region IDataSection Members
    //rispostaVaRPortafoglioType[] rispostaptfModello;

    public DataSectionResult getDataSection(List<SessionStruct> tabelleSessione, string querySql, DataThread dataThread)
    {
        try
        {
            FormatNum conv = new FormatNum();

            DataSectionResult dsr = new DataSectionResult();
            Random rnd = new Random();

            DataTable dt = new DataTable();
            DataSetS57 ds57 = new DataSetS57();
            DataSetS57.PatrimonioBFAreeBisognoRow tuplaMaggiore = null;
            decimal valoreMaggiore = 0;
            decimal valoreMaggioreControvalore = 0;
            decimal residuo = 100;
            decimal residuoControvalore = 0;
            DataSetS57.PatrimonioBFAreeBisognoRow tuplaControvalore = null;
            
            if (dataThread.Patrimoniobancafideuramctv != 0)
            {

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

                if(dt.Rows.Count==0) // non dovrebbe mai accadere per C6.
                    return dsr;


                Decimal ctvTotale = 0;
                Decimal ctvCC = 0;
                Decimal ctvNA = 0;

                DataSetS57.PartiteViaggiantiRow drPart;
                DataSetS57.TotaleAreeBisognoRow drTotAree;
               // DataSetS57.TotalePatrimonioRow drTotPat;
                DataSetS57.PatrimonioBFAreeBisognoRow dr;
                DataSetS57.ContoCorrenteRow drCc;
                DataSetS57.RisorseNonAssociateRow drNa;

                bool bPrimaRiga = true;
                FormatNum con = new FormatNum();

                ds57.PatrimonioBFAreeBisogno.Columns["ControvaloreModello"].Caption = "Controvalore <br> � &nbsp; &nbsp; &nbsp; &nbsp;";
                ds57.PatrimonioBFAreeBisogno.Columns["ControvaloreAttuale"].Caption = "Controvalore <br> � &nbsp; &nbsp; &nbsp; &nbsp;";
                ds57.PatrimonioBFAreeBisogno.Columns["DifferenzaEuro"].Caption = "Differenza <br> � &nbsp; &nbsp; &nbsp; &nbsp;";


                drPart = ds57.PartiteViaggianti.NewPartiteViaggiantiRow();
                drPart.Descrizione = Resource.PartiteViaggianti;               
                drPart.ControValore = dataThread.PartiteViaggiantiInvestimento + dataThread.PartiteViaggiantiDisinvestimento;
                if ((Decimal)drPart.ControValore != 0)
                    ds57.PartiteViaggianti.Rows.Add(drPart);
                //bool tuttiZeriAttuale = true;
                object sumPercAttuale = dt.Compute("Sum(PercentualeAttuale)", "");
                if (sumPercAttuale.ToString() == string.Empty)
                    sumPercAttuale = 0M;

                foreach (DataRow row in dt.Rows)
                {
                    if (bPrimaRiga)
                    {
                        //valorizzazione daatatable TotaleAreeBisogno
                        drTotAree = ds57.TotaleAreeBisogno.NewTotaleAreeBisognoRow();

                        drTotAree.DescrTotale = "TOTALE";
                        drTotAree.ControvaloreAttuale = Convert.ToDecimal(row["somma_controvalAttuale"]);
                        drTotAree.ControvaloreModello = Convert.ToDecimal(row["somma_controvalModello"]);
                        residuoControvalore = Convert.ToDecimal(row["somma_controvalModello"]);
                        
                        if(Convert.ToDecimal(sumPercAttuale) == 0.00M)
                            drTotAree.PercentualeAttuale = 0.00M;
                        else
                            drTotAree.PercentualeAttuale = 100.00M;

                        drTotAree.PercentualeModello = 100.00M;


                        if (row["copertura_tot_pirString"] != DBNull.Value)
                            drTotAree.GradoCopertura = row["copertura_tot_pirString"].ToString();
                        else
                            drTotAree.GradoCopertura = conv.ConvertNum(row["copertura_tot_pir"]);

                        if (row["var_tot_pirString"] != DBNull.Value)
                            drTotAree.Var = row["var_tot_pirString"].ToString();
                        else
                            drTotAree.Var = conv.ConvertNum(row["var_tot_pir"]);

                        if (row["somma_controvalAttuale"] == DBNull.Value)
                            ctvTotale += 0;
                        else
                            ctvTotale += (Decimal)row["somma_controvalAttuale"];

                        ds57.TotaleAreeBisogno.AddTotaleAreeBisognoRow(drTotAree);

                        bPrimaRiga = false;
                    }
                    //nota


                    // escludo risorse non allocate (na), contocorrente (cc) , pro, pre1 e pre2
                    if (row["needarea"].ToString().ToLower() != "na" && row["needarea"].ToString().ToLower() != "cc" && row["needarea"].ToString().ToLower() != "pro" && row["needarea"].ToString().ToLower() != "pre1" && row["needarea"].ToString().ToLower() != "pre2")
                    {

                        dr = ds57.PatrimonioBFAreeBisogno.NewPatrimonioBFAreeBisognoRow();
                        dr.CodiceAreaBisogno = row["needarea"].ToString();
                        dr.DescrAreaBisogno = row["areaname"].ToString();

                        dr.ControvaloreAttuale = Convert.ToDecimal(row["controvaloreAttuale"]);


                        //dr.ControvaloreModello = Convert.ToDecimal(row["controvaloreModello"]);
                        //V
                        decimal tempControvalore = Convert.ToDecimal(row["controvaloreModello"]);
                        //tempControvalore = decimal.Round(tempControvalore, 2);
                        dr.ControvaloreModello = tempControvalore;

                        if (tempControvalore > valoreMaggioreControvalore)
                        {
                            valoreMaggioreControvalore = tempControvalore;
                            tuplaControvalore = dr;
                        }

                        //
                        residuoControvalore -= tempControvalore;
                        //V
                        decimal temp = Convert.ToDecimal(row["percentualeAttuale"]);
                        temp = decimal.Round(temp, 2);
                        //dr.PercentualeAttuale = Convert.ToDecimal(row["percentualeAttuale"]);
                        dr.PercentualeAttuale = temp;

                        if (dr.PercentualeAttuale > valoreMaggiore)
                        {
                            valoreMaggiore = dr.PercentualeAttuale;
                            tuplaMaggiore = dr;
                            //dr.ItemArray.CopyTo(tuplaMaggiore.ItemArray.);
                            //tuplaMaggiore.ItemArray.CopyTo = dr.ItemArray.CopyTo(tuplaMaggiore.ItemArray);
                        }
                        residuo -= dr.PercentualeAttuale;
                        //
                        dr.PercentualeModello = Convert.ToDecimal(row["percentualeModello"]);
                        dr.DifferenzaEuro = Convert.ToDecimal(row["differenzaEuro"]);
                        dr.DifferenzaPercentuale = Convert.ToDecimal(row["differenzaPercentuale"]);

                        if (row["var_needareaString"] != DBNull.Value)
                            dr.Var = row["var_needareaString"].ToString();
                        else
                            dr.Var = conv.ConvertNum(row["var_needarea"]);

                        if (row["copertura_needareaString"] != DBNull.Value)
                            dr.GradoCopertura = row["copertura_needareaString"].ToString();
                        else
                            dr.GradoCopertura = conv.ConvertNum(row["copertura_needarea"]);

                        dr.Nota = Convert.ToInt32(row["Nota"]);

                        ds57.PatrimonioBFAreeBisogno.AddPatrimonioBFAreeBisognoRow(dr);
                    }
                }

                //
                if (residuoControvalore != 0 && tuplaControvalore != null)
                {
                    tuplaControvalore.ControvaloreModello += residuoControvalore;
                    tuplaControvalore.DifferenzaEuro -= residuoControvalore;
                }


                //V
                if (residuo != 0 && tuplaMaggiore != null)
                {
                    tuplaMaggiore.PercentualeAttuale += residuo;
                    tuplaMaggiore.DifferenzaPercentuale += residuo;
                    
                }
                //
                //foreach (DataRow tuple in ds57.PatrimonioBFAreeBisogno)
                //{
                //    tuple["differenzaPercentuale"] = tuple["percentualeAttuale"] - tuple["percentualeModello"];
                //}
                drNa = ds57.RisorseNonAssociate.NewRisorseNonAssociateRow();
                drNa.Descrizione = "Risorse non allocate";
                drNa.Controvalore = dataThread.RisorseNonAssociate;
                ctvNA += dataThread.RisorseNonAssociate;
                if (drNa.Controvalore != 0)
                    ds57.RisorseNonAssociate.AddRisorseNonAssociateRow(drNa);

                drCc = ds57.ContoCorrente.NewContoCorrenteRow();
                drCc.Descrizione = "Conto corrente";
                drCc.Controvalore = dataThread.ContoCorrente;
                ctvCC += dataThread.ContoCorrente;
                if (drCc.Controvalore != 0)
                    ds57.ContoCorrente.AddContoCorrenteRow(drCc);

                if ((ctvNA + ctvCC + dataThread.PartiteViaggiantiInvestimento + dataThread.PartiteViaggiantiDisinvestimento) != 0)
                {
                    DataRow drTot = ds57.TotalePatrimonio.NewRow();
                    drTot["DescrTotale"] = "TOT. PATRIMONIO";
                    drTot["Controvalore"] = ctvTotale + ctvNA + ctvCC + dataThread.PartiteViaggiantiInvestimento + dataThread.PartiteViaggiantiDisinvestimento;
                    ds57.TotalePatrimonio.Rows.Add(drTot);
                    
                }

                //V
                dataThread.TotaleS57 = ctvTotale + ctvNA + ctvCC -dataThread.PatrimonioNonRappresentabile; // +dataThread.PartiteViaggiantiInv;
                ////Normalizzo le percentuali
                //FormatNum conv = new FormatNum();
                //if (dt.Rows.Count != 0)
                //    conv.NormalizePerc(ds57.PatrimonioBFAreeBisogno, "PercentualeAttuale");
                //========================================================


                #region gestione della tabella TOTALE RISORSE FINANZIARIE e TOTALE RISORSE ALLOCATE.

                if (ds57.RisorseNonAssociate.Rows.Count == 0)
                {
                    //NON sono presenti risorse non allocate. 
                    // Rinomino il totale sotto la piramide  in TOTALE RISORSE FINANZIARIE            


                    DataSetS57.TotalePiramideRow rTotalePiramide;
                    rTotalePiramide = ds57.TotalePiramide.NewTotalePiramideRow();
                    rTotalePiramide.Descrizione = "TOTALE RISORSE FINANZIARIE";
                    rTotalePiramide.VaR = conv.ConvertNum(ds57.TotaleAreeBisogno[0]["Var"].ToString());
                    rTotalePiramide.CoperturaPercentuale = conv.ConvertNum(ds57.TotaleAreeBisogno[0]["GradoCopertura"].ToString());
                    rTotalePiramide.HasRisorseNonAllocate = false;
                    ds57.TotalePiramide.AddTotalePiramideRow(rTotalePiramide);
                }
                else
                {
                    //SONO presenti risorse non allocate. 
                    //rinominare il �TOTALE� sotto la piramide in �TOTALE RISORSE ALLOCATE�                

                    decimal varRisorsenonAllocate = dataThread.VaRRisorseNonAssociate;
                    decimal coperturaRisorseNonAllocate = dataThread.CoperturaRisorseNonAssociate;

                    decimal varTOTALERISORSEFINANZIARIE = dataThread.VaRTotaleRisorseFinanziarie;
                    decimal coperturaTOTALERISORSEFINANZIARIE = dataThread.CoperturaTotaleRisorseFinanziarie;


                    DataSetS57.TotalePiramideRow rTotalePiramide;
                    rTotalePiramide = ds57.TotalePiramide.NewTotalePiramideRow();
                    rTotalePiramide.Descrizione = "TOTALE RISORSE ALLOCATE";
                    rTotalePiramide.VaR = conv.ConvertNum(ds57.TotaleAreeBisogno[0]["Var"].ToString());
                    rTotalePiramide.CoperturaPercentuale = conv.ConvertNum(ds57.TotaleAreeBisogno[0]["GradoCopertura"].ToString());
                    rTotalePiramide.HasRisorseNonAllocate = true;
                    ds57.TotalePiramide.AddTotalePiramideRow(rTotalePiramide);

                    //introdurre la riga di �Risorse non allocate� con relativo VaR e Copertura
                    rTotalePiramide = ds57.TotalePiramide.NewTotalePiramideRow();
                    rTotalePiramide.Descrizione = "Risorse non allocate";
                    rTotalePiramide.VaR = conv.ConvertNum(varRisorsenonAllocate);
                    rTotalePiramide.CoperturaPercentuale = conv.ConvertNum(coperturaRisorseNonAllocate);
                    rTotalePiramide.HasRisorseNonAllocate = true;
                    ds57.TotalePiramide.AddTotalePiramideRow(rTotalePiramide);

                    rTotalePiramide = ds57.TotalePiramide.NewTotalePiramideRow();
                    rTotalePiramide.Descrizione = "TOTALE RISORSE FINANZIARIE";
                    rTotalePiramide.VaR = conv.ConvertNum(varTOTALERISORSEFINANZIARIE);
                    rTotalePiramide.CoperturaPercentuale = conv.ConvertNum(coperturaTOTALERISORSEFINANZIARIE);
                    rTotalePiramide.HasRisorseNonAllocate = true;
                    ds57.TotalePiramide.AddTotalePiramideRow(rTotalePiramide);
                }

                #endregion
            }          

            dsr.DatiSezione = ds57;
            dsr.Esito = ds57.PatrimonioBFAreeBisogno.Rows.Count;

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

    #endregion
}