using BeWo.Data.Access;
using BeWo.Data.Entities;
using BS.Shared.DataContracts;

namespace BeWo.Service.DCEntityMapper
{
    public class MedRecordDC_MedRecord : AbstractIDCEntityMapper<MedRecord, MedRecordDC>
    {
        public override MedRecordDC MergeWithDC(MedRecord pEntity, MedRecordDC pDataContract)
        {
            pDataContract.MedRecordOid = pEntity.Oid;
            pDataContract.MedRecordVersion = pEntity.Version;

            pDataContract.MedDate           = pEntity.MedDate;
            pDataContract.MedName           = pEntity.MedName;
            pDataContract.PrescribingDoctor = pEntity.PrescribingDoctor;
            pDataContract.Notice            = pEntity.Notice;

            if (pEntity.Customer != null)
            {
                pDataContract.Customer = MapperFactory.CompactCustomerDC_Customer.MapToNewDC(pEntity.Customer);
            }

            if (pEntity.Employee != null)
            {
                pDataContract.Employee = MapperFactory.CompactEmployeeDC_Employee.MapToNewDC(pEntity.Employee);
            }

            if (pEntity.DosageForm != null)
            {
                pDataContract.DosageForm = MapperFactory.DarreichungsformDC_Darreichungsform.MapToNewDC(pEntity.DosageForm);
            }

            return pDataContract;
        }

        public override MedRecord MergeWithEntity(MedRecordDC pDataContract, MedRecord pEntity)
        {
            ConcurrencyCheck(pDataContract.MedRecordVersion, pEntity);

            pEntity.MedDate           = pDataContract.MedDate;
            pEntity.MedName           = pDataContract.MedName;
            pEntity.PrescribingDoctor = pDataContract.PrescribingDoctor;
            pEntity.Notice            = pDataContract.Notice;

            if (pDataContract.Customer == null)
            {
                pEntity.Customer = null;
            }
            else if (pEntity.Customer == null || pEntity.Customer.Oid != pDataContract.Customer.CustomerOid)
            {
                pEntity.Customer = DAOFactory.GenericDAO.LoadByID<Customer>(pDataContract.Customer.CustomerOid);
            }

            if (pEntity.Employee == null || pEntity.Employee.Oid != pDataContract.Employee.EmployeeOid)
            {
                pEntity.Employee = DAOFactory.GenericDAO.LoadByID<Employee>(pDataContract.Employee.EmployeeOid);
            }

            if (pEntity.DosageForm == null || pEntity.DosageForm.Oid != pDataContract.DosageForm.DarreichungsformOid)
            {
                pEntity.DosageForm = DAOFactory.GenericDAO.LoadByID<Darreichungsform>(pDataContract.DosageForm.DarreichungsformOid.Value);
            }

            return pEntity;
        }

        protected override bool AreDCAndEntityEqual(MedRecordDC pDC, MedRecord pEntity)
        {
            if (pDC.MedRecordOid == null)
            {
                return false;
            }

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