using RX_Sample._00_API;
using System;

namespace RX_Sample._02_Mediator.Call
{
    public class CallModel : ICallModel
    {
        private readonly ICall appCall;
        private readonly IMediator mediator;

        public CallModel(
            ICall appCall,
            IMediator mediator)
        {
            this.appCall = appCall;
            this.mediator = mediator;

            appCall.CallStatusChanged += AppCall_CallStatusChanged;
            appCall.ContactIdChanged += AppCall_ContactIdChanged;
            appCall.CollaborationStarted += OnCollaborationStarted;
            appCall.CollaborationEnded += OnCollaborationEnded;
        }

        private void AppCall_ContactIdChanged(object sender, string e)
        {
            mediator.Notify(new CallMessage(CallMessageType.ContactIdChanged), appCall.CallId);
        }

        private void AppCall_CallStatusChanged(object sender, _00_API.CallStatus e)
        {
            mediator.Notify(new CallMessage(CallMessageType.CallStatusChanged), appCall.CallId);
        }

        private void OnCollaborationStarted(object sender, ICollaboration e)
        {
            mediator.Notify(new CollaborationMessage(true), appCall.CallId);
        }

        private void OnCollaborationEnded(object sender, ICollaboration e)
        {
            mediator.Notify(new CollaborationMessage(true), appCall.CallId);
        }

        public void Dispose()
        {
            appCall.CallStatusChanged -= AppCall_CallStatusChanged;
            appCall.ContactIdChanged -= AppCall_ContactIdChanged;
            appCall.CollaborationStarted -= OnCollaborationStarted;
            appCall.CollaborationEnded -= OnCollaborationEnded;
        }

        public string ContactId => appCall.ContactId;

        public ICollaborationModel Collaboration { get; private set; }
    }
}
