using RX_Sample._02_Mediator.Call;
using RX_Sample._02_Mediator.Contact;
using System;

namespace RX_Sample._02_Mediator
{
    public class CallInfoViewModel : IDisposable
    {
        private readonly ICallModel callModel;
        private readonly IMediator mediator;
        private readonly IContactManager contactManager;
        private readonly byte[] replacementAvatar = new byte[0];
        private readonly byte[] collaborationAvatar = new byte[0];

        public CallInfoViewModel(
            ICallModel callModel,
            IMediator mediator,
            IContactManager contactManager,
            IDispatcher dispatcher)
        {
            mediator.RegisterWithDispatcher<ContactMessage>(dispatcher, this, ContactMessageHandler);
            mediator.RegisterWithDispatcher<CallMessage>(dispatcher, this, CallMessageHandler);
            mediator.RegisterWithDispatcher<CollaborationMessage>(dispatcher, this, CollaborationMessageHandler);
            this.callModel = callModel;
            this.mediator = mediator;
            this.contactManager = contactManager;
            CalculateAvatar();
        }

        public byte[] Avatar { get; set; }

        private void ContactMessageHandler(ContactMessage contactMessage)
        {
            CalculateAvatar();
        }

        private void CallMessageHandler(CallMessage callMessage)
        {
            CalculateAvatar();
        }

        private void CollaborationMessageHandler(CollaborationMessage collaborationMessage)
        {
            CalculateAvatar();
        }

        private void CalculateAvatar()
        {
            if (callModel.Collaboration != null)
            {
                Avatar = collaborationAvatar;
            }

            if (string.IsNullOrEmpty(callModel.ContactId))
            {
                Avatar = replacementAvatar;
                return;
            }

            var contact = contactManager.GetContactById(callModel.ContactId);
            if (contact == null)
            {
                Avatar = replacementAvatar;
                return;
            }

            Avatar = contact.Avatar;
        }
        
        public void Dispose()
        {
            mediator.UnRegister<ContactMessage>(this);
            mediator.UnRegister<CallMessage>(this);
            mediator.UnRegister<CollaborationMessage>(this);
        }
    }
}
