using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Data;
using System.Web;
using ConsulenzaEvoluta;
using ClassLibraryWS.bancafideuram.nac.anagrafica;
using System.Web.UI.WebControls;

public partial class reportMappatura : System.Web.UI.Page
{
    public string codCliente;
    public string tipoRete;
    public string codPB;
    public string codAs;
    public string codiceUtenteQueryString;
    public string token;
    public string userName = string.Empty;
    public string codiceApplicazione = string.Empty;
    public string checkPrivacy;

    private Nucleo _nucleo;
    public string pathNav;
    public int idReport;              //indica il modello (fixed) COMPLETO di QUESTO report da cui costruire la treeview iniziale
    private string sUtente;
    public int chiaveClientePB;
    public static int tpReport = 8;        //valore proprietario (fixed) di QUESTO report //DA VALUTARE!!
    public static int idReportAlbero = 16; //valore proprietario (fixed) di QUESTO report //DA VALUTARE!!
    public static int idReportBase = 16;
    public static int idReportCompleto = 16;
    public string codiceRete;
    public string codicePB;
    public string ambiente;
    public int lastSavedReportId;
    public static string nomeReport = "PATRIMONIOIMMOBILLIARE";                   //valore proprietario (fixed) di QUESTO report
    public static string nomeReportCompleto = "Nucleo completo";  //valore proprietario (fixed) di QUESTO report 
    public static string nomeReportRischio = "NUCLEO";                   //valore proprietario (fixed) di QUESTO report
    public static string nomeReportBaseRischio = "Nucleo base";          //valore proprietario (fixed) di QUESTO report 
    public static string nomeReportCompletoRischio = "Nucleo completo";  //valore proprietario (fixed) di QUESTO report 

    public static string tabs1Href = "#tabs-1";
    public static string tabs2Href = "#tabs-2";
    public static string tabs3Href = "#tabs-3";
    public static string tabsTutteHref = "#tabs-Tutte";
    public static string tabs0Href = "#tabs0link";

    public static string blankHref = "#";

    string nomeReportPerLabel;
    string descrizioneReportPerLabel;
    public int reportIdToLoadBack = -1;
    public string endOfjob = "0";

    //private bool reportNominativo = false;
    int IDReportToLoad = -1;
    public string baseCompleto;
    public string reportName;

    private int IdModello;
    private GestReport m = new GestReport();

    public static bool IsNewTabRequired(int chiaveClientePB,out DataTable data)
    {
        List<Parametro> parametri = new List<Parametro>();
        parametri.Add(new Parametro() { ParameterName = "chiaveClientePB", Value = chiaveClientePB });
        data = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServerConsulenzaEvoluta, "GetClientsDataByChiaveClientePb", parametri);

        //return data.Rows.Count > 0;
        return data.Rows.Count > 1;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
       
        
        
        if (ClassLibraryWS.Debug.iSDebug && Request.QueryString.Get("tipoRete") == null)
        {
            // Test Mappatura
           //Response.Redirect("reportMappatura.aspx?codPB=044496&chiaveClientePB=2788&token=&tipoRete=I");
            // Test Mappatura Cointestatari - ChiaveClientePB 17 all cointestatari
            Response.Redirect("reportMappatura.aspx?codPB=017016&chiaveClientePB=26487&token=&tipoRete=I");
            return;
        }


        Session.Add("token", Request.QueryString.Get("token"));
        Session.Add("codiceRete", Request.QueryString.Get("tipoRete"));
        Session.Add("tipoRete", Request.QueryString.Get("tiporete"));
        Session.Add("codicePB", Request.QueryString.Get("codPB"));
        Session.Add("codPB", Request.QueryString.Get("codpb"));
        Session.Add("codAs", Request.QueryString.Get("codas"));
        Session.Add("chiaveClientePB",Request.QueryString["chiaveClientePB"]);
        
        Session.Add("newChiaveClientePB", Request.QueryString["newChiaveClientePB"]);



        try
        { 
        token = Request.QueryString.Get("token");
        codiceRete = Request.QueryString.Get("tipoRete");
        tipoRete = Request.QueryString.Get("tiporete").ToUpper();
        codicePB = Request.QueryString.Get("codPB");
        codPB = Request.QueryString.Get("codpb").ToUpper();
        codAs = Request.QueryString.Get("codas") != null ? Request.QueryString.Get("codas").ToUpper() : string.Empty;
        codiceUtenteQueryString = tipoRete.Trim() + codicePB.Trim();
        chiaveClientePB = Convert.ToInt32(Request.QueryString["chiaveClientePB"]);
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + ex.Message + "');</script>");
        }

        IdModello = codiceRete.Equals("S") ? 10 : 9;
        //vincoli
        //token = "32324";
        //codiceRete = "S";
        //tipoRete = "I";
        //codicePB = "044496";
        //codPB = "9998";
        //codAs = string.Empty;
        //codiceUtenteQueryString = tipoRete.Trim() + codicePB.Trim();
        //chiaveClientePB = 130;
        //IdModello = 9;

        if (!Page.IsPostBack)
        {
            var v = Session["newChiaveClientePB"];
            DataTable dt = new DataTable();
            
            bool newTab = IsNewTabRequired(chiaveClientePB, out dt);


            if (newTab && v == null)
            {
                // tabs0link.Visible = true;
                tabs0.Visible = true;
                testX.Visible = false;
                tabs1.HRef = blankHref;
                tabs2.HRef = blankHref;
                tabs3.HRef = blankHref;
                tabsTutte.HRef = blankHref;
                ButImportaTutto.Visible = false;

                string fullName = "";
               
                foreach (DataRow r in dt.Rows)
                {
                    var xv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
                    //HyperLink b = new HyperLink();

                    HyperLink b = new HyperLink();
                    b.Width = 600;
                    b.ID = r["chiaveclientepbFiglio"].ToString();
                    b.NavigateUrl = BuildURI(b.ID);
                    fullName += r["nomeCliente"].ToString() + ";";
                    b.Text = r["nomeCliente"].ToString();
                    b.Style.Add("margin-bottom", "10px");
                   // b.ImageUrl = "schede-1Fptma.jpg";
                    xv.Controls.Add(b);
                    tabs0link.Controls.Add(xv);
                }
                if (fullName != "")
                {
                    var xv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
                    HyperLink b = new HyperLink();


                    b.ID = dt.Rows[0]["chiaveclientepbPAdre"].ToString();
                    b.NavigateUrl = BuildURI(b.ID);
                    b.Width = 600;
                    b.Text = fullName.Substring(0,fullName.Length-1);
                    b.Style.Add("margin-bottom", "10px");
                    xv.Controls.Add(b);
                    tabs0link.Controls.Add(xv);
                }


            }
            else
            {
                tabs0.Visible = false;
                //tabs0link.Visible = false;
                tabs1.Style.Add("width", "110px");
                tabs2.Style.Add("width", "110px");
                tabs3.Style.Add("width", "110px");
                tabsTutte.Style.Add("width", "110px");
                testX.Visible = true;

                ButImportaTutto.Visible = true;
                tabs1.HRef = tabs1Href;
                tabs2.HRef = tabs2Href;
                tabs3.HRef = tabs3Href;
                tabsTutte.HRef = tabsTutteHref;

            }

            #region From Gestione Modelli
            //string loadingReport = Request.QueryString.Get("idReportToLoad");
            //nomeReportPerLabel = Request.QueryString.Get("nomeInizialeReport");
            //descrizioneReportPerLabel = Request.QueryString.Get("descrizioneInizialeReport");
            #endregion

            if (HFERRORMSG.Value.Equals(""))
            {

                m.TipoRete = codiceRete.Equals("I") ? "Intesa Sanpaolo Private Banking" : "SanPaolo Invest";
                m.AcquisisciModello(IdModello);
                m.AcquisisciElencoFabbricatiMappatura(chiaveClientePB);
            }


            List<string> vincoli = m.GetVincoliSchedeMappatura(chiaveClientePB);
            m.SetEnableSchede(vincoli);
            if (vincoli.Exists(item => item == "flagnosoloabitazionicatasto"))
            {
                foreach (SchedaReport sr in m.Modello)
                {
                    if (sr.Sezioni == "135")
                    {
                        sr.Vincoli += "&SEN_Per stampare la scheda 8 si necessita la deselezione di almeno un immobile della scheda 7, altrimenti eliminare la scheda 8 dal report";
                        break;
                    }
                }
            }

            DatiHidden.Value = m.GetHtmlClient();


            SessionGeneratorPdf spdf = new SessionGeneratorPdf(chiaveClientePB, null, "mappatura", null);

            if (ClassLibraryWS.Debug.iSDebug)
            {
                ClassLibraryWS.Debug.LogFunzionalita("iSDebug", "return forzato");
                return;
            }



            #region Recupero token da AnagraficaWS.GetVersion

            if (string.IsNullOrEmpty(token))
            {
                string codPortal = WebConfigParameter.getParameter("CODICEPORTALEPERVERSIONESIMPB");

                //InfoClient infoCliente = new InfoClient();
                ClassLibraryWS.bancafideuram.nac.token.InfoClient infoCliente = new ClassLibraryWS.bancafideuram.nac.token.InfoClient();
                infoCliente.codiceApplicazione = WebConfigParameter.getParameter("CODICEAPPLICAZIONE").ToString();
                infoCliente.codiceRete = codiceRete;
                infoCliente.versioneDatabaseSIMPB = 0;

                AnagraficaWS wsana = new AnagraficaWS();

                //ClassLibraryWS.bancafideuram.nac.token.InfoClient risposta = wsana.GetVersion(infoCliente, codPortal);
                ClassLibraryWS.bancafideuram.nac.token.TokenRes risposta = wsana.GetVersion(infoCliente, codPortal);
                token = risposta.info.versioneDatabaseSIMPB.ToString();


            }

            #endregion

            #region InfoClient e ChiaveCliente di GlobalPosition e Anagrafica

            // Global Position
            ClassLibraryWS.bancafideuram.nac.globalposition.InfoClient _infoCliente_GlobalPosition = new ClassLibraryWS.bancafideuram.nac.globalposition.InfoClient();
            _infoCliente_GlobalPosition.codiceApplicazione = WebConfigParameter.getParameter("CODICEAPPLICAZIONE").ToString();
            _infoCliente_GlobalPosition.versioneDatabaseSIMPB = int.Parse(token);


            ClassLibraryWS.bancafideuram.nac.globalposition.ChiaveCliente _chiaveCliente_GlobalPosition = new ClassLibraryWS.bancafideuram.nac.globalposition.ChiaveCliente();
            //_chiaveCliente_GlobalPosition.potenzialeClienteNAC = true;

            #endregion



            #region Gestione Autorizzazione

            if (WebConfigParameter.getParameter("Ambiente") == "esterno")
                userName = User.Identity.Name;
            else
                userName = WebConfigParameter.getParameter("UtenzaWindowsAccessoHP");

            //1) utente loggato (VINCENZO UT.PROVA 2 MAGRI)
            //2) utente impersonificato (VIOTTI GIANCARLO)

            string AbilitazionePrimaria = string.Empty;

            codiceApplicazione = WebConfigParameter.getParameter("CodiceApplicazione");

            //string codiceUtente = tipoRete + Utente.GetCodiceUtente(userName); // è il codiceutente con cui andrò a interrogare la ConsulenzaBase.dbo.PromotoreBancario per recuperare le informazioni dell'utente loggato
            string codiceUtente = tipoRete + codicePB;
            Utente utenteLoggato_WS = Utente.GetAutorizzazioniAccessoGestioneControlli(userName, codiceApplicazione); // utente loggato (VINCENZO UT.PROVA 2 MAGRI), informazioni prese dai WS
            Utente utenteLoggato = Utente.GetProfiloUtente(codiceUtente, utenteLoggato_WS.ProfiloUtenteLoggato); // utente loggato (VINCENZO UT.PROVA 2 MAGRI) , informazioni prese da DB
            utenteLoggato.ProfiloUtenteLoggato = utenteLoggato_WS.ProfiloUtenteLoggato;
            utenteLoggato.AbilitazionePrimaria = utenteLoggato_WS.AbilitazionePrimaria;
            utenteLoggato.IsUtenteImpersonificato = utenteLoggato_WS.IsUtenteImpersonificato;
            utenteLoggato.UtenteAutorizzatoApplicazione = utenteLoggato_WS.UtenteAutorizzatoApplicazione;

            Utente utenteImpersonificato = Utente.GetProfiloUtente(codiceUtenteQueryString, null); // utente impersonificato (VIOTTI GIANCARLO)
            utenteImpersonificato.AbilitazionePrimaria = utenteLoggato.AbilitazionePrimaria;
            utenteImpersonificato.IsUtenteImpersonificato = utenteLoggato.IsUtenteImpersonificato;
            utenteImpersonificato.UtenteAutorizzatoApplicazione = utenteLoggato.UtenteAutorizzatoApplicazione;

            // FIX da valutare per TK T-300675-L4Y3
            if (!codAs.Equals(codPB))
                codiceUtenteQueryString = codiceUtente;

            Utente utenteSoloPerAutorizzazione = Utente.GetAutorizzazioni(userName, codiceApplicazione, tipoRete, codiceUtenteQueryString, Convert.ToInt32(token));

            if (utenteSoloPerAutorizzazione.UtenteAutorizzatoApplicazione)
            {
                if (Request.Browser.Cookies)
                {
                    #region utente Loggato (UtenteLoggatoDiSessione)

                    string utenteLoggatoString = Utente.SerializeMessage(utenteLoggato);

                    utenteLoggatoString = HttpUtility.UrlDecode(utenteLoggatoString.TrimStart().TrimEnd());
                    Session.Add("UtenteLoggatoDiSessione", utenteLoggatoString);

                    #endregion

                    #region utente Impersonificato (UtenteImpersonificatoDiSessione)

                    string utenteImpersonificatoString = Utente.SerializeMessage(utenteImpersonificato);

                    utenteImpersonificatoString = HttpUtility.UrlDecode(utenteImpersonificatoString.TrimStart().TrimEnd());
                    Session.Add("UtenteImpersonificatoDiSessione", utenteImpersonificatoString);

                    #endregion
                }
                else
                {
                    AbilitazionePrimaria = string.Empty;
                    if (utenteLoggato != null)
                        if (utenteLoggato.AbilitazionePrimaria != null)
                            AbilitazionePrimaria = utenteLoggato.AbilitazionePrimaria;

                    Response.Redirect("error.aspx?UtenteWindows=" + userName + "&UtentePB=" + codiceUtenteQueryString + "&CodiceApplicazione=" + WebConfigParameter.getParameter("CODICEAPPLICAZIONE") + "&VersioneSIMPB=" + token.ToString() + "&AbilitazionePrimaria=" + AbilitazionePrimaria);
                }
            }
            else
            {
                AbilitazionePrimaria = string.Empty;
                if (utenteLoggato != null)
                    if (utenteLoggato.AbilitazionePrimaria != null)
                        AbilitazionePrimaria = utenteLoggato.AbilitazionePrimaria;

                Response.Redirect("error.aspx?UtenteWindows=" + userName + "&UtentePB=" + codiceUtenteQueryString + "&CodiceApplicazione=" + WebConfigParameter.getParameter("CODICEAPPLICAZIONE") + "&VersioneSIMPB=" + token.ToString() + "&AbilitazionePrimaria=" + AbilitazionePrimaria + "&UtenteAutorizzato=" + utenteLoggato_WS.UtenteAutorizzatoApplicazione.ToString());
            }


            #endregion



        }


    


    }

    private void B_Command(object sender, CommandEventArgs e)
    {
        throw new NotImplementedException();
    }

    private void B_Click(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }

    private string BuildURI(string sid)
    {
        
  
            string redirectString = "reportMappatura.aspx?";
            List<String> sessionItems = new List<string>();
            sessionItems.Add("token");
            sessionItems.Add("codiceRete");
            sessionItems.Add("tipoRete");
            sessionItems.Add("codicePB");
            sessionItems.Add("codPB");
            sessionItems.Add("codAs");
          //  sessionItems.Add("chiaveClientePB");
            //sessionItems.Add("newChiaveClientePB");

            foreach (String s in sessionItems)
            {
                redirectString += s + "=" + Session[s] + "&";

            }
        redirectString += "chiaveClientePB=" + sid;
        redirectString += "&newChiaveClientePB=" + sid; 
          
            return redirectString;
      
       
    }
}