using System.Linq;

using BeWo.Data.Entities;

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

namespace BeWo.Service.DCEntityMapper
{
    public class UserGroupDC_UserGroup : AbstractIDCEntityMapper<UserGroup, UserGroupDC>
    {
        public override UserGroupDC MergeWithDC(UserGroup pEntity, UserGroupDC pDataContract)
        {
            pDataContract.UserGroupOid = pEntity.Oid;
            pDataContract.UserGroupVersion = pEntity.Version;
            pDataContract.Name = pEntity.Name;
            pDataContract.Description = pEntity.Description;
            pDataContract.Rights = pEntity.Rights.Select(rr => rr.RightType).ToList();

            return pDataContract;
        }

        public override UserGroup MergeWithEntity(UserGroupDC pDataContract, UserGroup pEntity)
        {
            this.ConcurrencyCheck(pDataContract.UserGroupVersion, pEntity);

            pEntity.Oid = pDataContract.UserGroupOid;
            pEntity.Name = pDataContract.Name;
            pEntity.Description = pDataContract.Description;

            pEntity.Rights.RemoveRange(rr => !pDataContract.Rights.Contains(rr.RightType));
            pEntity.Rights.AddRange(pDataContract.Rights.Where(r => pEntity.Rights.SingleOrDefault(rr => rr.RightType == r) == null).Select(r => new RightRelation { RightType = r }));

            return pEntity;
        }

        protected override bool AreDCAndEntityEqual(UserGroupDC pDC, UserGroup pEntity)
        {
            if (pDC.UserGroupOid == null)
            {
                return false;
            }

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