using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace PDFGenerator.BusinessLayer.DataSection
{
    class DSS102DistribuzioneRischioCredito : IDataSection
    {
        #region IDataSection Members
        StructColor toBeFound = new StructColor();

        public DataSectionResult getDataSection(List<SessionStruct> tabelleSessione, string querySql, DataThread dataThread)
        {
            ////Mebaid
            //querySql = "[C6MartPeriodico].PL_S1Patrimonio";
            //// End Mebaid
            FormatNum num = new FormatNum();
            DataSectionResult dsr = new DataSectionResult();
            int foundIdx = 0;
            DataTable dt = null;

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

            
            dsr.Esito = dt.Rows.Count;
            if (dt.Rows.Count == 0)
            {
                return dsr;
            }

            toBeFound.Tipo = "Classi Rischio Credito";
            DataRow row;

            DataView ordina = new DataView(dt);
            ordina.Sort = "ordine";

            DataTable tabOrdinata = ordina.ToTable();

            if (dataThread.TipoReport.ToUpper() == "MONITORAGGIO")
            //prendo la prima ed unica riga del datatable
                row = tabOrdinata.Rows[0];
            else
            {
                if (dataThread.Intermediario.ToUpper() == "BF")
                    row = tabOrdinata.Rows[0];
                else
                {
                    DataRow[] rows = dt.Select(" INTERMEDIARIO  = '" + dataThread.Intermediario.Replace("'", "''") + "'");
                    row = rows[0];   
                }
            }

            DataSetS102 ds102 = new DataSetS102();
            //il colore è bianco
            ds102.RischioCredito.Columns["CounterValue"].Caption = "Controvalore <br> (€) &nbsp; &nbsp; &nbsp; &nbsp;";
            ds102.RischioCredito.Columns["Percentage"].Caption = "Peso <br> (%) &nbsp;";
            DataRow dr = ds102.RischioCredito.NewRow();

            //#762828	118	40	40
            //toBeFound.Codice = "RSKCL4";
            //foundIdx = ClsFunzioniGeneriche.findRightColors(toBeFound);
            //dr["RiskClassName"] = "Oltre Classe 3";
            //dr["CounterValue"] = num.ConvertNum(Convert.ToDecimal(row["CTV_overClass3"]));//V + dataThread.PartiteViaggiantiInv;
            //dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_OVERCLASS3"]),2,MidpointRounding.AwayFromZero);
            //dr["Red"] = ClsFunzioniGeneriche.Colors[foundIdx].Red;
            //dr["Green"] = ClsFunzioniGeneriche.Colors[foundIdx].Green;
            //dr["Blue"] = ClsFunzioniGeneriche.Colors[foundIdx].Blue;
            //ds102.RischioCredito.Rows.Add(dr);

            ////dati per grafico
            //dr = ds102.ChartData.NewRow();
            //dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_OVERCLASS3"]),2,MidpointRounding.AwayFromZero);
            //dr["PercentageFake"] = 0;//row["PatrimonioTerziCTV"];

            ////doppio colore perchè sulla prima riga del grafico e della tabella ci sono
            ////il patrimonio BF e il patrimonio Terzi
            //toBeFound.Codice = "RSKCL4";
            //foundIdx = ClsFunzioniGeneriche.findRightColors(toBeFound);

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

            //ds102.ChartData.Rows.Add(dr);
            //End Of Graph


            //toBeFound.Codice = "RSKCL3";
            //foundIdx = ClsFunzioniGeneriche.findRightColors(toBeFound);

            ////mebaid One Row
            ////Data Rows Start
            //dr = ds102.RischioCredito.NewRow();
            ////dr["RiskClassName"] = "Class 3";
            ////dr["CounterValue"] = row["CTV_Class3"];
            ////dr["Percentage"] = row["PERC_Class3"];
            //dr["RiskClassName"] = "Classe 3";
            //dr["CounterValue"] = num.ConvertNum(Convert.ToDecimal(row["CTV_Class3"]));
            //dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_CLASS3"]),2,MidpointRounding.AwayFromZero);
            //dr["Red"] = ClsFunzioniGeneriche.Colors[foundIdx].Red;
            //dr["Green"] = ClsFunzioniGeneriche.Colors[foundIdx].Green;
            //dr["Blue"] = ClsFunzioniGeneriche.Colors[foundIdx].Blue;
            //ds102.RischioCredito.Rows.Add(dr);

            ////dati per grafico
            //dr = ds102.ChartData.NewRow();
            ////dr["Percentage"] = row["ImmobiliareCTV"];
            //dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_CLASS3"]),2,MidpointRounding.AwayFromZero);
            //dr["Red"] = ClsFunzioniGeneriche.Colors[foundIdx].Red;
            //dr["Green"] = ClsFunzioniGeneriche.Colors[foundIdx].Green;
            //dr["Blue"] = ClsFunzioniGeneriche.Colors[foundIdx].Blue;
            //ds102.ChartData.Rows.Add(dr);

            //toBeFound.Codice = "RSKCL2";
            //foundIdx = ClsFunzioniGeneriche.findRightColors(toBeFound);



            //dr = ds102.RischioCredito.NewRow();
            ////dr["RiskClassName"] = "Altro";
            ////dr["CounterValue"] = row["CTV_Class2"];
            ////dr["Percentage"] = row["PERC_Class2"];
            //dr["RiskClassName"] = "Classe 2";
            //dr["CounterValue"] = num.ConvertNum(Convert.ToDecimal(row["CTV_Class2"]));
            //dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_CLASS2"]),2,MidpointRounding.AwayFromZero);
            //dr["Red"] = ClsFunzioniGeneriche.Colors[foundIdx].Red;
            //dr["Green"] = ClsFunzioniGeneriche.Colors[foundIdx].Green;
            //dr["Blue"] = ClsFunzioniGeneriche.Colors[foundIdx].Blue;
            //ds102.RischioCredito.Rows.Add(dr);

            ////dati per grafico
            //dr = ds102.ChartData.NewRow();
            //dr["Percentage"] = Convert.ToDecimal(row["PERC_CLASS2"]);//row["AltroCTV"];
            //dr["Red"] = ClsFunzioniGeneriche.Colors[foundIdx].Red;
            //dr["Green"] = ClsFunzioniGeneriche.Colors[foundIdx].Green;
            //dr["Blue"] = ClsFunzioniGeneriche.Colors[foundIdx].Blue;
            //ds102.ChartData.Rows.Add(dr);



            //toBeFound.Codice = "RSKCL1";
            toBeFound.Codice = "RSKCL4";
            foundIdx = ClsFunzioniGeneriche.findRightColors(toBeFound);

            dr = ds102.RischioCredito.NewRow();
            //dr["RiskClassName"] = "Classe 1";
            dr["RiskClassName"] = "Soggetto a valutazione di Rischio Credito";
            //dr["CounterValue"] = num.ConvertNum(Convert.ToDecimal(row["CTV_Class1"]));
            dr["CounterValue"] = num.ConvertNum(Convert.ToDecimal(row["CTV_CreditRisk"]));//V + dataThread.PartiteViaggiantiInv;
            //dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_CLASS1"]), 2, MidpointRounding.AwayFromZero);
            dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_CreditRisk"]), 2, MidpointRounding.AwayFromZero);
            dr["Red"] = ClsFunzioniGeneriche.Colors[foundIdx].Red;
            dr["Green"] = ClsFunzioniGeneriche.Colors[foundIdx].Green;
            dr["Blue"] = ClsFunzioniGeneriche.Colors[foundIdx].Blue;
            ds102.RischioCredito.Rows.Add(dr);

            //dati per grafico
            dr = ds102.ChartData.NewRow();
            //dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_CLASS1"]), 2, MidpointRounding.AwayFromZero); //row["AltroCTV"];
            dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_CreditRisk"]), 2, MidpointRounding.AwayFromZero);
            dr["Red"] = ClsFunzioniGeneriche.Colors[foundIdx].Red;
            dr["Green"] = ClsFunzioniGeneriche.Colors[foundIdx].Green;
            dr["Blue"] = ClsFunzioniGeneriche.Colors[foundIdx].Blue;
            ds102.ChartData.Rows.Add(dr);




            //#D1DEE0	209	222	224
            toBeFound.Codice = "RSKCL0";
            foundIdx = ClsFunzioniGeneriche.findRightColors(toBeFound);

            dr = ds102.RischioCredito.NewRow();
            //dr["RiskClassName"] = "Non Applicabile";
            dr["RiskClassName"] = "Non soggetto a valutazione di Rischio Credito";
            dr["CounterValue"] = num.ConvertNum(Convert.ToDecimal(row["CTV_na"]));
            dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_na"]),2);
            dr["Red"] = ClsFunzioniGeneriche.Colors[foundIdx].Red;
            dr["Green"] = ClsFunzioniGeneriche.Colors[foundIdx].Green;
            dr["Blue"] = ClsFunzioniGeneriche.Colors[foundIdx].Blue;
            ds102.RischioCredito.Rows.Add(dr);

            //dati per grafico
            dr = ds102.ChartData.NewRow();
            dr["Percentage"] = Convert.ToDecimal(row["PERC_na"]); //row["AltroCTV"];
            dr["Red"] = ClsFunzioniGeneriche.Colors[foundIdx].Red;
            dr["Green"] = ClsFunzioniGeneriche.Colors[foundIdx].Green;
            dr["Blue"] = ClsFunzioniGeneriche.Colors[foundIdx].Blue;
            ds102.ChartData.Rows.Add(dr);

            if (Convert.ToDecimal(row["CTV_Notcovered"]) > 0)
            {

                // covered row
                DataRow Covered = ds102.PatrimonioCoperto.NewRow();
                Covered["RiskclassName"] = "Patrimonio coperto";

                decimal Total = 0;
                for (int i = 0; i < ds102.RischioCredito.Rows.Count; i++)
                    Total = Total + decimal.Parse(ds102.RischioCredito.Rows[i]["CounterValue"].ToString());

                Covered["CounterValue"] = Total; // +dataThread.PartiteViaggiantiInv;

                decimal TotalPeso = 0;

                //V
                //Algoritmo di approssimazione del centesimo nel caso di patrimonio non coperto
                DataRow tuplaMaggiore = ds102.RischioCredito.Rows[0];
                decimal valoreMaggiore = 0;
                bool bFlag = false;
                for (int i = 0; i < ds102.RischioCredito.Rows.Count; i++)
                {
                    decimal temp = Convert.ToDecimal(ds102.RischioCredito.Rows[i]["Percentage"]);
                    TotalPeso = TotalPeso + temp;
                    if (temp > valoreMaggiore)
                    {
                        tuplaMaggiore = ds102.RischioCredito.Rows[i];
                        valoreMaggiore = temp;
                        bFlag = true;
                    }
                }


                //Not covered row
                DataRow notCovered = ds102.PatrimonioNonCoperto.NewRow();
                notCovered["RiskclassName"] = "Patrimonio non coperto";
                
                notCovered["CounterValue"] = Convert.ToDecimal(row["CTV_Notcovered"]);  // +dataThread.PartiteViaggiantiInv;
                //notCovered["Percentage"] = Decimal.Round(Convert.ToDecimal(row["Perc_notcovered"]),2,MidpointRounding.AwayFromZero);

                //decimal delta = 100 - Convert.ToDecimal(notCovered["Percentage"]) - TotalPeso;
                decimal delta = 100 - TotalPeso;
                if (delta != 0)
                {
                    if (bFlag)
                    {
                        tuplaMaggiore["Percentage"] = Convert.ToDecimal(tuplaMaggiore["Percentage"]) + delta;
                        TotalPeso += delta;
                    }
                    else
                    {
                        tuplaMaggiore["Percentage"] = Convert.ToDecimal(tuplaMaggiore["Percentage"]);
                        //TotalPeso += delta;
                    }
                }

                ds102.PatrimonioNonCoperto.Rows.Add(notCovered);

                Covered["Percentage"] = TotalPeso;
                ds102.PatrimonioCoperto.Rows.Add(Covered);


            }

            else //Algoritmo di approssimazione 
            {
                //V
                //Algoritmo di approssimazione del centesimo nel caso di patrimonio coperto
                decimal TotalPeso = 0;
                DataRow tuplaMaggiore = ds102.RischioCredito.Rows[0];
                decimal valoreMaggiore = 0;
                for (int i = 0; i < ds102.RischioCredito.Rows.Count; i++)
                {
                    decimal temp = Convert.ToDecimal(ds102.RischioCredito.Rows[i]["Percentage"]);
                    TotalPeso = TotalPeso + temp;
                    if (temp > valoreMaggiore)
                    {
                        tuplaMaggiore = ds102.RischioCredito.Rows[i];
                        valoreMaggiore = temp;
                    }
                }

                decimal delta = 100 - TotalPeso;
                if (delta != 0)
                {
                    tuplaMaggiore["Percentage"] = Convert.ToDecimal(tuplaMaggiore["Percentage"]) + delta;
                }
            }


            FormatNum formatter = new FormatNum();
            // TOTAL ROW
            DataRow drTot = ds102.RischioCreditoTotal.NewRow();
            drTot["Totale"] = "Patrimonio totale";
            //drTot["CounterValue"] = formatter.ConvertNum(Convert.ToDecimal(row["CTV_TOT"])) + "*"; // +dataThread.PartiteViaggiantiInv;
            decimal totalePartiteViaggianti = dataThread.PartiteViaggiantiInvestimento + dataThread.PartiteViaggiantiDisinvestimento;
            if (
                (dataThread.TotalNegativeCurrentAccountValue < 0 || totalePartiteViaggianti != 0) 
                &&  
                (dataThread.Intermediario.ToUpper() == "COMPLESSIVO" || dataThread.Intermediario.ToUpper() == "BF")
                &&
                (dataThread.TipoReport.ToUpper() == TipoReport.DIAGNOSI.ToString())
                )
            {
                drTot["CounterValue"] = formatter.ConvertNum(Convert.ToDecimal(row["CTV_TOT"])) + "*";
            }
            else if (
                (dataThread.TotalNegativeCurrentAccountValue < 0 || totalePartiteViaggianti != 0) 
                &&  
                (dataThread.TipoReport.ToUpper() == TipoReport.MONITORAGGIO.ToString())
                )
            {
                drTot["CounterValue"] = formatter.ConvertNum(Convert.ToDecimal(row["CTV_TOT"])) + "*";
            }
            else
            {
                drTot["CounterValue"] = formatter.ConvertNum(Convert.ToDecimal(row["CTV_TOT"])); 
            }
            //drTot["CounterValue"] = row["CTV_TOT"].ToString() + "(*)";
            if (Convert.ToDecimal(row["CTV_Notcovered"]) == 0)
                drTot["Percentage"] = 100;

            ds102.RischioCreditoTotal.Rows.Add(drTot);

            dsr.DatiSezione = ds102;
            dsr.Esito = dt.Rows.Count;
            return dsr;
        }
        #endregion
    }
}