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

using BS.Shared;
using BS.Shared.DataContracts;

namespace BeWo.Service.DCEntityMapper
{
    public class CustomerPersonRelationDC_Customer2Person : AbstractIDCEntityMapper<Customer2Person, CustomerPersonRelationDC>
    {
        public override CustomerPersonRelationDC MergeWithDC(Customer2Person pEntity, CustomerPersonRelationDC pDataContract)
        {
            if (pEntity.ValueList.Count > 0)
            {
                pDataContract.RelationRole = MapperFactory.ValueListEntryDC_ValueListEntry.MapToNewDC(pEntity.ValueList[0].Entry);
            }

            pDataContract.Customer2PersonNotice = pEntity.Notice;
            pDataContract.Customer2PersonOid = pEntity.Oid;
            pDataContract.Customer2PersonVersion = pEntity.Version;
            pDataContract.Person = MapperFactory.CompactPersonDC_Person.MapToNewDC(pEntity.Person);

            if (pDataContract.Person != null && pEntity.Person.Contacts != null)
            {
                foreach (var contact in pEntity.Person.Contacts)
                {

                    if (contact.Type == ContactType.private_Mail)
                    {
                        pDataContract.Person.Communication3 = contact.Value;
                    }

                    if (contact.Type == ContactType.private_Fax)
                        {
                            pDataContract.Person.Communication4 = contact.Value;
                        }

                    if (contact.Type == ContactType.private_Phone)
                        {
                            pDataContract.Person.Communication1 = contact.Value;
                        }

                    if (contact.Type == ContactType.private_MobilePhone)
                    {
                        pDataContract.Person.Communication2 = contact.Value;
                    }

                }
            }
            
            return pDataContract;
        }

        public override Customer2Person MergeWithEntity(CustomerPersonRelationDC pDataContract, Customer2Person pEntity)
        {
            MapperFactory.ValueListEntryDC_ValueListEntry.MapUniqueTypeValueListEntryBack2Entity(pDataContract.RelationRole, pEntity.ValueList, ValueListEntryType.EnvironmentPersonType, TableID.Customer2Person);

            pEntity.Oid = pDataContract.Customer2PersonOid;
            pEntity.Version = pDataContract.Customer2PersonVersion;
            pEntity.Notice = pDataContract.Customer2PersonNotice;

            pEntity.Person = DAOFactory.GenericDAO.LoadByID<Person>(pDataContract.Person.PersonOid);

            return pEntity;
        }

        protected override bool AreDCAndEntityEqual(CustomerPersonRelationDC pDC, Customer2Person pEntity)
        {
            if (pDC.Customer2PersonOid == null)
            {
                return false;
            }

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