using System;
using System.Collections.Generic;
using System.Linq;
using Consulenza.ReportWriter.Business;
using Consulenza.ReportWriter.Business.OBJ_PDF;
using System.Data;
using Consulenza.ReportWriter.Business.Entity;

namespace Consulenza.ReportWriter.Manager.Section.Immobiliare.Diagnosi.Nucleo
{
    /// <summary>
    /// Dettaglio immobili con anomalie catastali (id 40)
    /// </summary>
    public class S8 : Immobiliare.Diagnosi.S8
    {
        public S8(EnvironmentFacade environmentFacade, int idSection)
            : base(environmentFacade, idSection)
        {
        }

        /// <summary>
        /// Recupera i dati necessari alla Section restituendo un DataTable.
        /// </summary>
        /// <returns></returns>
        protected override DataTable GetDataTable()
        {
            #region Definizione dei parametri

            var parametri = new List<Parametro>
            {
                new Parametro
                {
                    Direction = ParameterDirection.Input,
                    DbType = DbType.Int64,
                    ParameterName = "ChiaveNucleo",
                    Value = EnvironmentFacade.ReportEnvironment.NucleoImmobiliare.ChiaveNucleo
                }
            };

            #endregion

            var dt = EnvironmentFacade.ReportEnvironment.NucleoImmobiliare.ImmobiliareCEUnica ? DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServerConsulenzaUnica, "REP_Nucleo_Immobiliare_S8_DettImmobiliAnomalieCatastali", parametri)
                : DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServerConsulenzaEvoluta, "REP_Nucleo_Immobiliare_S8_DettImmobiliAnomalieCatastali", parametri);
            

            //Riaggregazione
            var query = (from p in dt.AsEnumerable()
                         group p by p.Field<string>("IdImmobileCatasto") into g
                         select new
                         {
                             IdImmobileCatasto = g.Key,
                             Descrizione = g.Select(x => x.Field<string>("Descrizione")).FirstOrDefault(),
                             ValoreStimato = g.Select(x => x.Field<decimal>("ValoreStimato")).FirstOrDefault(),
                             AnomalieRilevate = string.Join("<BR><BR>", g.Select(x => x.Field<string>("AnomalieRilevate")))
                         }).ToList();


            var dtResult = dt.Clone();

            foreach (var item in query)
                dtResult.Rows.Add(item.IdImmobileCatasto, item.Descrizione, item.ValoreStimato, string.Empty, item.AnomalieRilevate);


            return dtResult;
        }
    }
}
