using System.Data;
using Consulenza.ReportCommon;
using System;

namespace Consulenza.ReportWriter.Manager.Integration
{
    /// <summary>
    /// Ridefinisce la struttura del report in funzione degli IdImmobileCatasto selezionati dall'utente, duplicandone il capitolo di riferimento. 
    /// </summary>
    public class DuplicazioneIdImmobileCatasto : IntegrationLayout
    {
        /// <summary>
        /// Imposta o recupera l'idImmobileCatasto corrente.
        /// </summary>
        public string IdImmobileCatasto { get; set; }

        /// <summary>
        /// Costruttore
        /// </summary>
        /// <param name="structure"></param>
        /// <param name="row"></param>
        /// <param name="environment"></param>
        public DuplicazioneIdImmobileCatasto(DataTable structure, DataRow row, ReportEnvironment environment)
            : base(structure, row, environment)
        {
            DuplicaCapitolo = true;

            if (structure.Columns.Contains("IdImmobileCatasto"))
                IdImmobileCatasto = row["IdImmobileCatasto"].ToString();
        }

        /// <summary>
        /// Ridefinisce la struttura del report in funzione degli IdImmobileCatasto selezionati dall'utente
        /// </summary>
        public override DataTable RecalculateStructure()
        {
            var copyReportStructure = ReportStructure.Clone();

            copyReportStructure.Columns.Add("IdImmobileCatasto", typeof(string));

            int rowIndex = 0;
            var listaIdimmobili = Environment.Immobiliare.IdImmobileCatasto ?? Environment.NucleoImmobiliare.IdImmobileCatasto ?? Environment.MappaturaPreliminare.IdImmobileCatasto ?? Environment.FinalitaImmobiliare.IdImmobileCatasto;
            foreach (var item in listaIdimmobili)
            {
                copyReportStructure.ImportRow(Row);
                copyReportStructure.Rows[rowIndex]["IdImmobileCatasto"] = item;
                rowIndex++;
            }

            // Rimuovo la Row corrente
            ReportStructure.Rows.Remove(Row);
            ReportStructure.AcceptChanges();

            // Merge
            ReportStructure.Merge(copyReportStructure);

            //Ordinamento
            var query = from rs in ReportStructure.AsEnumerable()
                        orderby rs.Field<Int32>("Ordine")
                        select rs;

            // Ritorno la struttura
            return query.AsDataView().ToTable();
        }
    }
}
