﻿using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using Microsoft.ServiceBus.Messaging;
using OnCallRota.Commands;
using OnCallRota.Data;

namespace OnCallRota.BusWorker.Handlers
{
    public class RenewTeamMemberMessageHandler : IMessageHandler
    {
        private readonly OnCallContext _context;

        public RenewTeamMemberMessageHandler(OnCallContext context)
        {
            _context = context;
        }

        public void Receive(BrokeredMessage receivedMessage)
        {
            var request = receivedMessage.GetBody<RenewTeamMember>();

            var teams = _context.Teams.Include("Members");

            if (request.Message.ToLower().StartsWith("confirm"))
            {
                var member = teams.SelectMany(team => team.Members).FirstOrDefault(m => m.PhoneNumber == request.Phone);
                if (member != null)
                {
                    _context.TeamMembers.Attach(member);
                    member.PendingRenewalConfirmation = false;
                    _context.Entry(member).State = EntityState.Modified;

                }
            }
            _context.SaveChanges();

            Trace.TraceInformation("Renewed team member, phone: {0}, message:{1}", request.Phone, request.Message);
        }
    }
}