using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Configuration;
using System.Web;
using LetteraAccompagnamento;
using DataAccessLayer;
using PDFGenerator.BusinessLayer;

public class GestoreLettera
{
    private GestoreLettera() { }
    public GestoreLettera(DataAccessDE dataAccess, DataThread dataThread)
    {
        this.dataAccess = dataAccess;
        this._dataThread = dataThread; 
    }
    private DataAccessDE dataAccess;
    private DataThread _dataThread;
    int idLettera = -1;
    string testo = string.Empty;
    LetteraBenvenuto w = null;
    string indirizzo = string.Empty;
    string nome = string.Empty;
    string cognome = string.Empty;
    //string codiceContratto = string.Empty;
    string appellativo = string.Empty;
    string oggetto = string.Empty;
    string firma = string.Empty;
    int codiceLettera = 0;
    /**** Fix Direct Bank 28/03/2023 - Pino ***/
    public int idModello { get; set; }
    /******************************************/

    public object objectLock = new object();
    public void RestGestoreLettera()
    {
        idLettera = -1;
        testo = string.Empty;
        w = null;
        indirizzo = string.Empty;
        nome = string.Empty;
        cognome = string.Empty;
        //string codiceContratto = string.Empty;
        appellativo = string.Empty;
        oggetto = string.Empty;
        firma = string.Empty;
        codiceLettera = 0;
    }
    private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
    public byte[] componiLetteraBenvenuto(string cf, string rete, TipoLettera tipo, TipoContratto tc, LetteraAccompagnamento.TipoReport tr, int idReport, bool isProffesional, DataThread _dataThread)
    {
        leggiDaDB(cf, rete, tipo, tc, tr, idReport, false, false, isProffesional);

        switch (codiceLettera)
        {
            case 1:
            case 2:
            case 200:
            case 201:
            case 204:
            case 205:
                w = new LetteraAccettazioneConAttivazioneSei(rete, idLettera, testo, nome, cognome, indirizzo, appellativo, oggetto, firma, tc,_dataThread);
                break;

            case 3:
            case 4:
            case 202:
            case 203:
            case 206:
            case 207:

            //Adriano 20171212: codici per lettere con accorpamento Contestuale / Non contestuale
            case 302: // SEI SanPaolo Invest
            case 303: // SEI Fideuram
            case 306: // SEI Private SanPaolo Invest
            case 307: // SEI Private Fideuram
            case 310: // SEI IWBank Andrea Modifica
            case 311: // SEI Private Andrea Modifica
            case 312: // SEI Direct Bank
                w = new LetteraAccettazioneAttivazioneSeiPosticipata(rete, idLettera, testo, nome, cognome, indirizzo, appellativo, oggetto, firma, tc,idModello,_dataThread);
                break;

            case 5:
            case 6:
                w = new LetteraRistampa(rete, idLettera, testo, nome, cognome, indirizzo, appellativo, oggetto, firma, tc,_dataThread);
                break;

        }
        testout += " " + cf + " " + rete + " " + codiceLettera;
        w.writePDF();
        return w.Data;

    }
    public List<byte[]> componiLetteraCommerciale(string cf, string rete, TipoLettera tipo, TipoContratto tc, LetteraAccompagnamento.TipoReport tr, int idReport, bool isProffesional)
    {
        List<byte[]> pages = new List<byte[]>();
        var letterPages = leggiDaDB(cf, rete, tipo, tc, tr, idReport, true, true, isProffesional);

        foreach (var w in letterPages)
        {
            testout += " " + cf + " " + rete + " " + codiceLettera;
            w.writePDF();
            pages.Add(w.Data);
        }
        return pages;
    }
    public string testout = "";

    public byte[] componiLetteraBenvenuto(string cf, string rete, TipoLettera tipo, TipoContratto tc, LetteraAccompagnamento.TipoReport tr, bool isProffesional)
    {
        return componiLetteraBenvenuto(cf, rete, tipo, tc, tr, -1, isProffesional, _dataThread);
    }

    public List<byte[]> componiLetteraCommerciale(string cf, string rete, TipoLettera tipo, TipoContratto tc, LetteraAccompagnamento.TipoReport tr, bool isProffesional)
    {
        return componiLetteraCommerciale(cf, rete, tipo, tc, tr, -1, isProffesional);
    }


    public byte[] componiLetteraAccompagnamento(string cf, string rete, TipoContratto tc, LetteraAccompagnamento.TipoReport tipo, bool isProffesional)
    {

        leggiDaDB(cf, rete, TipoLettera.ReportPeriodico, tc, tipo, -1, true, false, isProffesional);

        while (w == null)
        {
            if (rete == "S")
                w = new LetteraAccompagnamentoPeriodico(rete, idLettera, testo, nome, cognome, indirizzo, appellativo, oggetto, firma, tc);
            else
                w = new LetteraAccompagnamentoPeriodico(rete, idLettera, testo, nome, cognome, indirizzo, appellativo, oggetto, firma, tc);
        }

        w.writePDF();
        return w.Data;
    }

    // 20190126 Per lettera errata corrige
    public byte[] componiLetteraErrataCorrige(string cf, string rete, TipoContratto tc, LetteraAccompagnamento.TipoReport tipo, bool isProffesional)
    {
        leggiDaDB(cf, rete, TipoLettera.ReportPeriodico, tc, tipo, -1, true, false, isProffesional, true);

        //w = new LetteraErrataCorrige(rete, idLettera, testo, nome, cognome, indirizzo, appellativo, oggetto, firma, tc, true);
        w = new LetteraErrataCorrige(rete, idLettera, testo, nome, cognome, indirizzo, appellativo, oggetto, firma, tc);

        testout += " " + cf + " " + rete + " " + codiceLettera;
        w.writePDF();
        return w.Data;

    }
    //--20190126


    //public  byte[] componiLetteraRistampa(string cf, string rete, TipoReport tr, int idReport, bool periodico)
    //{
    //    leggiDaDB(cf, rete, TipoLettera.RistampaLettera, tr, idReport, periodico);
    //    w = new LetteraRistampa(rete, idLettera, testo, nome, cognome, indirizzo, appellativo, oggetto, firma);
    //    w.writePDF();
    //    return w.Data;
    //}


    private List<LetteraCommerciale> leggiDaDB(string cf, string rete, TipoLettera tipo, TipoContratto tipoContratto, LetteraAccompagnamento.TipoReport tr, int idReport, bool periodico, bool isCommercial = false, bool isProffesional = false)
    {
        string nomestored = "";
        List<LetteraCommerciale> results = new List<LetteraCommerciale>();
        
        try
        {
            List<Parametro> parametri = new List<Parametro>();
            Parametro p = new Parametro();
            p.DbType = DbType.AnsiString;
            p.Value = rete;
            p.ParameterName = "rete";
            parametri.Add(p);
            p = new Parametro();
            p.DbType = DbType.AnsiString;
            p.Value = cf;
            p.ParameterName = "cf";
            parametri.Add(p);

            p = new Parametro();
            p.DbType = DbType.AnsiString;
            p.Value = idReport;
            p.ParameterName = "idReport";
            parametri.Add(p);



            p = new Parametro();
            p.DbType = DbType.AnsiString;
            p.Value = (tr == LetteraAccompagnamento.TipoReport.Diagnosi) ? "Diagnosi" : "Monitoraggio";
            p.ParameterName = "tipoReport";
            parametri.Add(p);

            
            if (periodico)
            {
                //nomestored = "[C6MartPeriodico].[GESTIONE_SELECT_LETTERE_DA_INVIARE]";
                nomestored = "[C6MartPeriodico].[GESTIONE_SELECT_LETTERE_DA_INVIARE_Rosaspina]";

                if (tipoContratto == TipoContratto.Old)
                {
                    if (tr == LetteraAccompagnamento.TipoReport.Diagnosi)
                    {
                        if (rete.ToUpper() == "S")
                            codiceLettera = 109;//Old Sanpaolo Diagnosi
                        // ************************* Modifica IWBank Andrea ********************************//
                        else if (rete.ToUpper() == "W")
                            codiceLettera = 107;
                        // *********************************************************************************//
                        else 
                            codiceLettera = 106;//Old Fideuram Diagnosi
                    }
                    else
                    {
                        if (rete.ToUpper() == "S")
                            codiceLettera = 103;//Old Sanpaolo Monitoraggio
                        else if (rete.ToUpper() == "W")
                            // ************************* Modifica IWBank Andrea ********************************//
                            codiceLettera = 112;
                        // *********************************************************************************//
                        else
                            codiceLettera = 100;//Old Fideuram Monitoraggio
                    }
                }

                if (tipoContratto == TipoContratto.Affluent)
                {
                    if (tr == LetteraAccompagnamento.TipoReport.Diagnosi)
                    {
                        if (rete.ToUpper() == "S")
                            codiceLettera = 110;//Affluent Sanpaolo Diagnosi
                        // ************************* Modifica IWBank Andrea ********************************//
                        else if (rete.ToUpper() == "W")
                            codiceLettera = 107;
                        // *********************************************************************************//
                        else
                            codiceLettera = 107;//Affluent Fideuram Diagnosi
                    }
                    else
                    {
                        if (rete.ToUpper() == "S")
                            codiceLettera = 104;//Old Sanpaolo Monitoraggio
                        else if (rete.ToUpper() == "W")
                         // ************************* Modifica IWBank Andrea ********************************//
                            codiceLettera = 112;
                        // *********************************************************************************//
                        else
                            codiceLettera = 101;//Old Fideuram Monitoraggio
                    }
                }

                if (tipoContratto == TipoContratto.Private)
                {
                    if (isCommercial)
                    {
                        if (rete.ToUpper() == "F")
                        {
                            codiceLettera = 301;
                        }
                    }
                    else
                    {
                        if (tr == LetteraAccompagnamento.TipoReport.Diagnosi)
                        {
                            if (rete.ToUpper() == "S")
                                codiceLettera = 111;//Private Sanpaolo Diagnosi
                            else
                                codiceLettera = 118;//Private Fideuram Diagnosi
                        }
                        else
                        {
                            if (rete.ToUpper() == "S")
                                codiceLettera = 105;//Private Sanpaolo Monitoraggio
                        // ************************* Modifica IWBank Andrea ********************************//
                             else if (rete.ToUpper() == "W")
                            codiceLettera = 108;
                        // *********************************************************************************//
                            else
                                codiceLettera = 102;//Private Fideuram Monitoraggio
                        }
                    }
                }
            }
            else
            {
                nomestored = "[C6Mart].[GESTIONE_SELECT_LETTERE_DA_INVIARE_Rosaspina]";//[C6Mart].[GESTIONE_SELECT_LETTERE_DA_INVIARE]
                if (tipo == TipoLettera.RistampaLettera)
                {
                    if (rete.ToUpper() == "S")
                        codiceLettera = 5;
                    else
                        codiceLettera = 6;
                }
                else
                {
                    // Adriano 20171212: PER LA NUOVA GESTIONE LETTERA UNIFICATA (CONTESTUALE/NON CONTESTUALE)
                    // non ci sar� pi� bisogno di differenziare tra TipoLettera.LetteraAccettazioneConAttivazioneSei e TipoLettera.LetteraAccettazioneAttivazioneSeiPosticipata

                    // I codici sono i seguenti:
                    // Contratto SEI

                    //          SanPaolo: 402
                    //          Fideuram: 403

                    // Contratto SEI Private

                    //          SanPaolo: 404
                    //          Fideuram: 405


                    if (tipoContratto == TipoContratto.Affluent || tipoContratto == TipoContratto.Old)
                    {
                        if (rete.ToUpper().Equals("S"))
                            codiceLettera = 302;
                        // ************************* Modifica IWBank Andrea ********************************//
                        else if (rete.ToUpper() == "W")
                            codiceLettera = 310;
                        // *********************************************************************************//
                        else
                        {
                            /*** Fix Direct Banker 28/03/2023 - Pino *****/
                            //codiceLettera = 303;
                            if (idModello != 6)
                                codiceLettera = 303;
                            else
                                codiceLettera = 312;
                            /********************************************/
                        }
                            
                    }

                    if (tipoContratto == TipoContratto.Private)
                    {
                        if (rete.ToUpper().Equals("S"))
                            codiceLettera = 306;
                        // ************************* Modifica IWBank Andrea ********************************//
                        else if (rete.ToUpper() == "W")
                            codiceLettera = 311;
                        // *********************************************************************************//
                        else
                        {
                            /*** Fix Direct Banker 28/03/2023 - Pino *****/
                            //codiceLettera = 307;
                            if (idModello != 6)
                                codiceLettera = 307;
                            else
                                codiceLettera = 312;
                            /************************************************/
                        }
                            
                    }

                    if (tipoContratto == TipoContratto.Dadvisory)
                    {
                        codiceLettera = 312;
                    }

                    // VECCHIA GESTIONE SEI / SEI PRIVATE + CONTESTUALE / NON CONTESTUALE + 'S'/'F'
                    //if (tipoContratto == TipoContratto.Affluent)
                    //{           
                    //    if (tipo == TipoLettera.LetteraAccettazioneConAttivazioneSei)
                    //    {
                    //        if (rete.ToUpper() == "S")
                    //            codiceLettera = 200;    //Affluent Contestuale Sampaolo  100
                    //        else
                    //            codiceLettera = 201;    //Affluent Contestuale Fideuram  101
                    //    }
                    //    if (tipo == TipoLettera.LetteraAccettazioneAttivazioneSeiPosticipata)
                    //    {
                    //        if (rete.ToUpper() == "S")
                    //            codiceLettera = 202;    //Affluent Posticipata Sampaolo 102
                    //        else
                    //            codiceLettera = 203;    //Affluent Posticipata Fideuram 103	
                    //    }
                    //}

                    //if (tipoContratto == TipoContratto.Private)
                    //{
                    //    if (tipo == TipoLettera.LetteraAccettazioneConAttivazioneSei)
                    //    {
                    //        if (rete.ToUpper() == "S")
                    //            codiceLettera = 204;//Private Contestuale Sampaolo  104
                    //        else
                    //            codiceLettera = 205;//Private Contestuale Fideuram 105
                    //    }
                    //    if (tipo == TipoLettera.LetteraAccettazioneAttivazioneSeiPosticipata)
                    //    {
                    //        if (rete.ToUpper() == "S")
                    //            codiceLettera = 206;//Private Posticipata Sampaolo 106
                    //        else
                    //            codiceLettera = 207;//Private Posticipata Fideuram 107
                    //    }
                    //}
                }
            }

            //codiceLettera = 201;
            p = new Parametro();
            p.DbType = DbType.Int16;
            p.Value = codiceLettera;
            p.ParameterName = "codiceLettera";
            parametri.Add(p);




            using (IDataReader lettere = dataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, nomestored, parametri))
            {
                while (lettere.Read())
                {
                    testo = lettere["testo"].ToString();

                    if (isProffesional)
                    {
                        //20180912 Su richiesta di Flavia Scirocco
                        //testo = testo.Replace("investimenti, di collocamento e di distribuzione", "investimenti, di collocamento e di distribuzione dedicati ai CLIENTI PROFESSIONALI");
                        testo = testo.Replace("investimenti, di collocamento e di distribuzione", "investimenti, di collocamento e di distribuzione per i clienti professionali");
                    }

                    indirizzo = lettere["via"].ToString() + "\r\n";

                    if (!string.IsNullOrEmpty(lettere["cap"].ToString()))
                        indirizzo += lettere["cap"].ToString() + " ";
                    else
                        indirizzo += lettere["cap"].ToString();

                    indirizzo += lettere["localita"].ToString();

                    //  indirizzo = lettere["via"].ToString() + "\r\n" +
                    //lettere["cap"].ToString() + " " +
                    //             lettere["localita"].ToString();

                    if (!string.IsNullOrEmpty(lettere["provincia"].ToString()))

                        indirizzo += " (" + lettere["provincia"].ToString() + ")";
                    nome = lettere["nome"].ToString();
                    cognome = lettere["cognome"].ToString();
                    appellativo = lettere["appellativo"].ToString();
                    oggetto = lettere["oggetto"].ToString();
                    firma = lettere["firma"].ToString();
                    int currentPageNumber = (int)lettere["pagina"];
                    //V

                    /*** Fix per conservare il tipo idModello per FD 22/05/2023 - Pino ***/
                    //var letterPage = new LetteraCommerciale(rete, idLettera, testo, nome, cognome, indirizzo, appellativo, oggetto, firma, tipoContratto, currentPageNumber);
                    var letterPage = new LetteraCommerciale(rete, idLettera, testo, nome, cognome, indirizzo, appellativo, oggetto, firma, tipoContratto, currentPageNumber,idModello,_dataThread);
                    /*********************************************************************/
                    results.Add(letterPage);
                }
                if (results.Count == 0)
                {
                    logger.Error(String.Concat("DataReader vuoto dopo l'esecuzione della stored procedure:", rete, cf));
                }

                if (!lettere.IsClosed)
                {
                    lettere.Close();
                    lettere.Dispose();
                }
            }
        }
        catch (Exception ex)
        {
            string errmes = "Errore nel Generatore della Lettera di Benvenuto: " + getException(ex) + " codfiscale " + cf + " rete " + rete + " lettera " + codiceLettera;
            ScriviErroreNelDB(-292929, errmes, -292929, "Generatore Lettera Benvenuto", "Generatore Lettera Benvenuto");
            Console.WriteLine(errmes);
            logger.Error(errmes);
        }

        return results;
    }

    /*
    private  void leggiDaDB(string cf, string rete, TipoLettera tipo, TipoReport tr, int idReport, bool periodico)
    {
        List<Parametro> parametri = new List<Parametro>();
        Parametro p = new Parametro();
        p.DbType = DbType.AnsiString;
        p.Value = rete;
        p.ParameterName = "rete";
        parametri.Add(p);
        p = new Parametro();
        p.DbType = DbType.AnsiString;
        p.Value = cf;
        p.ParameterName = "cf";
        parametri.Add(p);

        p = new Parametro();
        p.DbType = DbType.AnsiString;
        p.Value = idReport;
        p.ParameterName = "idReport";
        parametri.Add(p);


        if (tipo == TipoLettera.LetteraAccettazioneConAttivazioneSei)
            if (rete.ToUpper() == "S")
                codiceLettera = 1;
            else
                codiceLettera = 2;

        if (tipo == TipoLettera.LetteraAccettazioneAttivazioneSeiPosticipata)
            if (rete.ToUpper() == "S")
                codiceLettera = 3;
            else
                codiceLettera = 4;

        if (tipo == TipoLettera.RistampaLettera)
            if (rete.ToUpper() == "S")
                codiceLettera = 5;
            else
                codiceLettera = 6;

        p = new Parametro();
        p.DbType = DbType.AnsiString;
        p.ParameterName = "tipoReport";
        parametri.Add(p);
        p.Value = string.Empty;

        if (periodico)
        {
            if (tr == TipoReport.Diagnosi)
                p.Value = "Diagnosi";
            else
                p.Value = "Monitoraggio";

            if (rete.ToUpper() == "S")
                codiceLettera = 7;
            else
                codiceLettera = 8;
        }
        else
            p.Value = "Diagnosi";


        p = new Parametro();
        p.DbType = DbType.Int16;
        p.Value = codiceLettera;
        p.ParameterName = "codiceLettera";
        parametri.Add(p);


        //START
        try
        {
            IDataReader lettere;
            if (periodico)
                lettere = DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, "[C6MartPeriodico].[GESTIONE_SELECT_LETTERE_DA_INVIARE]", parametri);
            else
                lettere = DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, "[C6Mart].[GESTIONE_SELECT_LETTERE_DA_INVIARE]", parametri);


            if (lettere.Read())
            {

                //idLettera = Convert.ToInt32(lettere["id"]);
                testo = lettere["testo"].ToString();
                indirizzo = lettere["via"].ToString() + "\r\n" +
                            lettere["cap"].ToString() + " " +
                            lettere["localita"].ToString();
                if (!string.IsNullOrEmpty(lettere["provincia"].ToString()))

                    indirizzo += " (" + lettere["provincia"].ToString() + ")";
                nome = lettere["nome"].ToString();
                cognome = lettere["cognome"].ToString();
                appellativo = lettere["appellativo"].ToString();
                oggetto = lettere["oggetto"].ToString();
                firma = lettere["firma"].ToString();
                //V
                if (!lettere.IsClosed)
                {
                    lettere.Close();
                    lettere.Dispose();
                }
                //
            }

            else
                throw new Exception("DataReader vuoto dopo l'esecuzione della stored procedure: [C6Mart].[GESTIONE_SELECT_LETTERE_DA_INVIARE]");

        }
        catch (DataBaseException ex)
        {
            //StartTng(ambiente, cawTo_Bin, argomentiCawToErrore);
            Console.WriteLine(ex.Message);
            if (HttpContext.Current == null)
                ScriviErroreNelDB(-292929, "Errore nel Generatore della Lettera di Benvenuto: " + getDataBaseException(ex), -292929, "Generatore Lettera Benvenuto", "Generatore Lettera Benvenuto");
            else
                throw ex;
            //return null;
        }
        catch (Exception ex)
        {
            //StartTng(ambiente, cawTo_Bin, argomentiCawToErrore);
            Console.WriteLine(ex.Message);
            if (HttpContext.Current == null)
                ScriviErroreNelDB(-292929, "Errore nel Generatore della Lettera di Benvenuto: " + getException(ex), -292929, "Generatore Lettera Benvenuto", "Generatore Lettera Benvenuto");
            else
                throw ex;

        }


    }
    */

    // 20190126 Gestione Lettera Errata Corrige
    private List<LetteraCommerciale> leggiDaDB(string cf, string rete, TipoLettera tipo, TipoContratto tipoContratto, LetteraAccompagnamento.TipoReport tr, int idReport, bool periodico, bool isCommercial = false, bool isProffesional = false, bool errataCorrige = true)
    {
        string nomestored = "";
        List<LetteraCommerciale> results = new List<LetteraCommerciale>();

        try
        {
            List<Parametro> parametri = new List<Parametro>();
            Parametro p = new Parametro();
            p.DbType = DbType.AnsiString;
            p.Value = rete;
            p.ParameterName = "rete";
            parametri.Add(p);
            p = new Parametro();
            p.DbType = DbType.AnsiString;
            p.Value = cf;
            p.ParameterName = "cf";
            parametri.Add(p);

            p = new Parametro();
            p.DbType = DbType.AnsiString;
            p.Value = idReport;
            p.ParameterName = "idReport";
            parametri.Add(p);



            p = new Parametro();
            p.DbType = DbType.AnsiString;
            p.Value = (tr == LetteraAccompagnamento.TipoReport.Diagnosi) ? "Diagnosi" : "Monitoraggio";
            p.ParameterName = "tipoReport";
            parametri.Add(p);


            if (periodico)
            {
                //  nomestored = "[C6MartPeriodico].[GESTIONE_SELECT_LETTERE_DA_INVIARE]";
                nomestored = "[C6MartPeriodico].[GESTIONE_SELECT_LETTERE_DA_INVIARE]";

                codiceLettera = rete.ToUpper().Equals("F") ? 601 : 602;

            }
            else
            {
             //   nomestored = "[C6Mart].[GESTIONE_SELECT_LETTERE_DA_INVIARE]";
                nomestored = "[C6Mart].[GESTIONE_SELECT_LETTERE_DA_INVIARE_Rosaspina]";


                codiceLettera = rete.ToUpper().Equals("F") ? 601 : 602;
            }


            //codiceLettera = 201;
            p = new Parametro();
            p.DbType = DbType.Int16;
            p.Value = codiceLettera;
            p.ParameterName = "codiceLettera";
            parametri.Add(p);

            string sqlString = string.Format("{0} '{1}', '{2}', {3}, {4}, '{5}'", nomestored, rete, cf, codiceLettera, idReport, tr);

            DataTable lettere = dataAccess.ExecuteDataTableSqlStatement(DBProvider.SqlServerStampeC6, sqlString, null);

            //using (DataTable lettere = dataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServerStampeC6, nomestored, parametri))
            //{
            foreach (DataRow row in lettere.Rows)
            {
                testo = row["testo"].ToString();

                indirizzo = row["via"].ToString() + "\r\n";

                if (!string.IsNullOrEmpty(row["cap"].ToString()))
                    indirizzo += row["cap"].ToString() + " ";
                else
                    indirizzo += row["cap"].ToString();

                indirizzo += row["localita"].ToString();

                //  indirizzo = lettere["via"].ToString() + "\r\n" +
                //lettere["cap"].ToString() + " " +
                //             lettere["localita"].ToString();

                if (!string.IsNullOrEmpty(row["provincia"].ToString()))

                    indirizzo += " (" + row["provincia"].ToString() + ")";
                nome = row["nome"].ToString();
                cognome = row["cognome"].ToString();
                appellativo = row["appellativo"].ToString();
                oggetto = row["oggetto"].ToString();
                firma = row["firma"].ToString();
                int currentPageNumber = (int)row["pagina"];
                //V

                //var letterPage = new LetteraErrataCorrige(rete, idLettera, testo, nome, cognome, indirizzo, appellativo, oggetto, firma, tipoContratto, true);
                var letterPage = new LetteraCommerciale(rete, idLettera, testo, nome, cognome, indirizzo, appellativo, oggetto, firma, tipoContratto, currentPageNumber, 0,_dataThread);
                results.Add(letterPage);

            }


            if (results.Count == 0)
            {
                logger.Error(String.Concat("DataTable vuota dopo l'esecuzione della stored procedure:", rete, cf));
            }

        }
        catch (Exception ex)
        {
            string errmes = "Errore nel Generatore della Lettera di Benvenuto: " + getException(ex) + " codfiscale " + cf + " rete " + rete + " lettera " + codiceLettera;
            ScriviErroreNelDB(-292929, errmes, -292929, "Generatore Lettera Benvenuto", "Generatore Lettera Benvenuto");
            Console.WriteLine(errmes);
            logger.Error(errmes);
        }

        return results;
    }

    //--20190126

    private string getDataBaseException(DataBaseException ecc)
    {
        const string aCapo = "#/n#";
        string ritorno = "";
        ritorno += aCapo;
        ritorno += "  Informazioni Comando SQL:" + aCapo;
        ritorno += "    sql file name: " + ecc.SqlFileName + aCapo;
        ritorno += "    connection string: " + ecc.ConnectionStringWithoutCredentials + aCapo;
        //ritorno += "    command text: " + ecc.CommandText + aCapo;
        //controllo se ci sono i parametri
        if (ecc.Parameters != null)
        {
            foreach (Parametro parametro in ecc.Parameters)
            {
                ritorno += aCapo;
                ritorno += "     parametro: " + parametro.ParameterName + aCapo;
                ritorno += "     dimensione: " + parametro.Size.ToString() + aCapo;
                ritorno += "     direzione: " + parametro.Direction.ToString() + aCapo;
                ritorno += "     tipo: " + parametro.DbType.ToString() + aCapo;

                if (parametro.Value == null)
                    ritorno += "     valore: null" + aCapo;
                else
                {
                    string valoreParametro = "";
                    if (parametro.Size > 500)
                    {
                        valoreParametro = "     valore: null(sono visualizzati solo i primi 500 bytes): " + parametro.Value.ToString().Substring(0, 500);
                    }
                    else
                    {
                        valoreParametro = "     valore: " + parametro.Value.ToString();
                    }
                    ritorno += valoreParametro + aCapo;
                }
            }
        }
        ritorno += aCapo;
        ritorno += "    tipo: DataBaseException" + aCapo;
        ritorno += "    descrizione: " + ecc.Eccezione.Message + aCapo;
        ritorno += "    sorgente: " + ecc.Eccezione.Source + aCapo;
        ritorno += "    traccia: " + FormattaErrore(ecc.StackTrace) + aCapo;
        return ritorno;

    }

    private string getException(Exception ecc)
    {
        const string aCapo = "#/n#";
        string ritorno = "";
        ritorno += aCapo;
        ritorno += "    tipo: " + ecc.GetType().ToString() + aCapo;
        ritorno += "    descrizione: " + ecc.Message + aCapo;
        ritorno += "    sorgente: " + ecc.Source + aCapo;
        if (ecc.InnerException != null)
        {
            ritorno += "    descrizione Inner: " + ecc.InnerException.Message + aCapo;
            ritorno += "    sorgente Inner: " + ecc.InnerException.Source + aCapo;
        }
        ritorno += "    traccia: " + FormattaErrore(ecc.StackTrace) + aCapo;
        return ritorno;

    }

    private string FormattaErrore(string errore)
    {
        const string aCapo = "#/n#";
        const string spazio = "      ";
        string separatore1 = " at ";
        string separatore2 = " in ";
        string separatore3 = ":line ";
        string erroreInterno = errore.Replace(separatore1, "@");
        string ritorno = aCapo;


        //nome metodo e tutto il resto
        string[] messaggioErrore = erroreInterno.Split('@');
        string messaggioSenzaSpazi;
        string[] messaggioInterno;

        foreach (string messaggio in messaggioErrore)
        {
            messaggioSenzaSpazi = messaggio.Trim();

            if (messaggioSenzaSpazi != "")
            {
                messaggioSenzaSpazi = messaggioSenzaSpazi.Replace(separatore2, "@");
                messaggioInterno = messaggioSenzaSpazi.Split('@');
                if (messaggioInterno.GetUpperBound(0) == 1)
                {
                    ritorno += spazio + "metodo: " + messaggioInterno[0] + aCapo;
                    string fileLineaSingolo = messaggioInterno[1].Replace(separatore3, "@");
                    string[] fileLinea = fileLineaSingolo.Split('@');
                    ritorno += spazio + "percorsoFile: " + fileLinea[0] + aCapo;
                    ritorno += spazio + "linea: " + fileLinea[1] + aCapo;
                    ritorno += aCapo;
                }
                else
                {
                    ritorno += spazio + "metodo: " + messaggioInterno[0] + aCapo;
                }
            }
        }

        return ritorno;
    }

    private void ScriviErroreNelDB(int codiceErrore, string descrizioErrore, int localeId, string nomePackage, string descrizionePackage)
    {
        int scriviErroreNelDB = int.Parse(ConfigurationManager.AppSettings["scriviErroreNelDB"]);
        if (scriviErroreNelDB == 1)
        {
            try
            {
                List<Parametro> parametri = new List<Parametro>();
                Parametro parametro = new Parametro();
                parametro.DbType = DbType.Int32;
                parametro.ParameterName = "codiceErrore";
                parametro.Value = codiceErrore;
                parametri.Add(parametro);

                parametro = new Parametro();
                parametro.DbType = DbType.String;
                parametro.ParameterName = "descrizioErrore";
                parametro.Value = descrizioErrore;
                parametri.Add(parametro);

                parametro = new Parametro();
                parametro.DbType = DbType.DateTime;
                parametro.ParameterName = "dataTime";
                parametro.Value = DateTime.Now;
                parametri.Add(parametro);

                parametro = new Parametro();
                parametro.DbType = DbType.String;
                parametro.ParameterName = "localeID";
                if (localeId == 0)
                    parametro.Value = System.DBNull.Value;
                else
                    parametro.Value = localeId;
                parametri.Add(parametro);

                parametro = new Parametro();
                parametro.DbType = DbType.String;
                parametro.ParameterName = "descrizionePackage";
                parametro.Value = descrizionePackage;
                parametri.Add(parametro);

                parametro = new Parametro();
                parametro.DbType = DbType.String;
                parametro.ParameterName = "nomePackage";
                parametro.Value = nomePackage;
                parametri.Add(parametro);

                DataAccess.ExecuteNonQueryStoredProcedure(DBProvider.SqlServerStampeC6, "[C6Mart].[UT_INSERT_ERROR]", parametri);
            }
            catch (Exception ex)
            {
                DataBaseException dataBaseException = (DataBaseException)ex;
                Console.WriteLine(dataBaseException.Message);
            }
        }
    }
}