using BeWo.Data.Access;
using BeWo.Data.Entities;

using BS.Shared.DataContracts;

namespace BeWo.Service.DCEntityMapper
{
    public class ServiceInvoiceDC_ServiceInvoice : AbstractIDCEntityMapper<ServiceInvoice, ServiceInvoiceDC>
    {
        public override ServiceInvoiceDC MergeWithDC(ServiceInvoice pEntity, ServiceInvoiceDC pDataContract)
        {
            pDataContract.AmountAdvancePayments = pEntity.AmountAdvancePayments;
            pDataContract.AmountEquityContribution = pEntity.AmountEquityContribution;
            pDataContract.ServiceInvoiceVersion = pEntity.Version;
            pDataContract.ServiceInvoiceOid = pEntity.Oid;
            pDataContract.InvoiceBase = MapperFactory.InvoiceBaseDC_InvoiceBase.MapToNewDC(pEntity.InvoiceBase);
            pDataContract.ServiceInvoicePeriods = MapperFactory.ServiceInvoicePeriodDC_ServiceInvoicePeriod.MapToNewDCs(pEntity.ServiceInvoicePeriodList);
            if (pEntity.ServiceUnitOid.HasValue)
            {
                pDataContract.ServiceUnit = MapperFactory.CostRatePeriodDC_CostRatePeriod
                    .MapToNewDC(DAOFactory.GenericDAO.LoadByID<CostRatePeriod>(pEntity.ServiceUnitOid.Value));
            }

            return pDataContract;
        }

        public override ServiceInvoice MergeWithEntity(ServiceInvoiceDC pDataContract, ServiceInvoice pEntity)
        {
            pEntity.AmountAdvancePayments = pDataContract.AmountAdvancePayments;
            pEntity.AmountEquityContribution = pDataContract.AmountEquityContribution;

            this.ConcurrencyCheck(pDataContract.ServiceInvoiceVersion, pEntity);

            if (pDataContract.InvoiceBase.InvoiceBaseOid.HasValue)
            {
                pEntity.InvoiceBase = MapperFactory.InvoiceBaseDC_InvoiceBase
                    .MergeWithEntity(pDataContract.InvoiceBase, 
                                     DAOFactory.GenericDAO.LoadByID<InvoiceBase>(pDataContract.InvoiceBase.InvoiceBaseOid.Value));
            }
            else
            {
                pEntity.InvoiceBase = MapperFactory.InvoiceBaseDC_InvoiceBase.MapToNewEntity(pDataContract.InvoiceBase);
            }

            MapperFactory.ServiceInvoicePeriodDC_ServiceInvoicePeriod.MergeWithEntitys(pDataContract.ServiceInvoicePeriods, 
                                                                                       pEntity.ServiceInvoicePeriodList);
            if (pDataContract.ServiceUnit != null)
            {
                pEntity.ServiceUnitOid = pDataContract.ServiceUnit.CostRatePeriodOid;
            }

            return pEntity;
        }

        protected override bool AreDCAndEntityEqual(ServiceInvoiceDC pDC, ServiceInvoice pEntity)
        {
            if (pDC.ServiceInvoiceOid == null)
            {
                return false;
            }

            return pDC.ServiceInvoiceOid == pEntity.Oid;
        }
    }
}