/// <summary>
        /// Create a new event
        /// </summary>
        /// <returns></returns>
        public ActionResult Create()
        {
            try
            {
                var dataModel = new Event
                    {
                        StartDate = DateTime.Now.Date.AddHours(19), //7:00 PM
                        EndDate = DateTime.Now.Date.AddHours(21), //9:00 pm
                        PeopleWhoAccepted = new List<Person>(),
                        PeopleWhoDeclined = new List<Person>(),
                        RegisteredInvites = new List<Person>()
                    };

                var model = GetViewModel(dataModel);
                var userName = (User != null) ? User.Identity.Name : string.Empty;
                var personId = _userService.GetCurrentUserId(userName);
                var thePerson = _personRepository.GetAll().FirstOrDefault(x => x.PersonId == personId);

                //Setup session
                SetupSession(GetEventById(0), thePerson);

                return View(model);
            }
            catch (Exception)
            {
                //TODO: log in database
                ViewBag.StatusMessage = GetMessageFromMessageId(BaseControllerMessageId.BuildViewModelFail);
            }

            return View();
        }
        public void Notification_On_Event_Cancelled()
        {
            //Arrange
            var theHost = new Person { PersonId = 3, FirstName = "Matt", LastName = "Harmin" };
            var peopleList = new List<Person>
                {
                    new Person {PersonId = 1, FirstName = "Joe", LastName = "Smith" },
                    new Person {PersonId = 2, FirstName = "Sally", LastName = "Hardy" },
                };

            var theEvent = new Event
            {
                EventId = 1,
                Title = "My Test Event",
                StartDate = DateTime.Now,
                Coordinator = theHost,
                RegisteredInvites = peopleList
            };

            A.CallTo(() => EventRepo.GetAll()).Returns(new List<Event> { theEvent }.AsQueryable());
            A.CallTo(() => PersonRepo.GetAll()).Returns(peopleList.AsQueryable());
            A.CallTo(() => InvitationRepo.GetAll()).Returns(new List<PendingInvitation>().AsQueryable());

            //Act
            var notification = NotifyService.GetNotificationForEventCancelled(theEvent.EventId, 1, 0);

            //Assert
            string hostName = string.Format("{0} {1}", theHost.FirstName, theHost.LastName);
            string expectedMessage = string.Format(Constants.MESSAGE_CANCELLED_TEMPLATE, theEvent.Title,
                                                    hostName);

            Assert.AreEqual(notification.Title, Constants.MESSAGE_CANCELLED_TITLE);
            Assert.AreEqual(notification.Message, expectedMessage);
        }
        public void Notification_On_Attendee_Removed()
        {
            //Arrange
            var theHost = new Person { PersonId = 3, FirstName = "Matt", LastName = "Harmin" };
            var thePerson = new Person{PersonId = 1, FirstName = "Joe", LastName = "Smith", NotifyWithFacebook = true, NotifyWithEmail = false};
            var theEvent = new Event { EventId = 1, Title = "My Test Event", StartDate = DateTime.Now, Coordinator = theHost };
            var personList = new List<Person>{thePerson};
            var eventList = new List<Event>{theEvent};

            A.CallTo(() => PersonRepo.GetAll()).Returns(personList.AsQueryable());
            A.CallTo(() => EventRepo.GetAll()).Returns(eventList.AsQueryable());
            A.CallTo(() => InvitationRepo.GetAll()).Returns(new List<PendingInvitation>().AsQueryable());

            //Act
            var notification = NotifyService.GetPersonRemovedFromEventNotification(theEvent.EventId, thePerson.PersonId, 0);

            //Assert
            string hostName = string.Format("{0} {1}", theHost.FirstName, theHost.LastName);
            string expectedMessage = string.Format(Constants.MESSAGE_REMOVE_TEMPLATE, hostName,
                                                    theEvent.Title, theEvent.StartDate.ToShortDateString(),
                                                    theEvent.StartDate.ToShortTimeString());

            Assert.AreEqual(notification.SendToEmail, personList[0].NotifyWithEmail);
            Assert.AreEqual(notification.SendToFacebook, personList[0].NotifyWithFacebook);
            Assert.AreEqual(notification.Title, Constants.MESSAGE_REMOVE_TITLE);
            Assert.AreEqual(notification.Message, expectedMessage);
        }
        public void Add_Food_Items()
        {
            //Arrange
            var chips = new FoodItem { FoodItemId = 1, Title = "Chips" };
            var candy = new FoodItem { FoodItemId = 2, Title = "Candy" };
            var pizza = new FoodItem { FoodItemId = 3, Title = "Pizza" };
            var milk = new FoodItem { FoodItemId = 4, Title = "Milk" };

            var model = new EventBaseViewModel
            {
                AllEventFoodItems = new List<FoodItemViewModel>
                    {
                        new FoodItemViewModel(chips),
                        new FoodItemViewModel(candy)
                    },
                WillBringTheseFoodItems = new List<FoodItemViewModel>(new[] { new FoodItemViewModel(pizza), new FoodItemViewModel(milk),  }), // this is what the user is bringing
            };

            //These are in the database
            var dataModel = new Event
            {
                Coordinator = new Person { MyFoodItems = new List<FoodItem> { pizza, milk } },
                FoodItems = new List<FoodItem> { chips, candy } // Pizza and milk will be added
            };

            A.CallTo(() => FoodRepo.GetAll()).Returns(new List<FoodItem>{ chips, candy, pizza, milk }.AsQueryable());

            //Act
            EventService.AppendNewFoodItems(dataModel, model);

            //Assert
            Assert.AreEqual(dataModel.FoodItems.Count, 4); //only the candy is removed.
        }
        public void AppendNewGames(Event dataModel, EventBaseViewModel viewModel)
        {
            var dataGameIds = dataModel.Games.Select(x => x.GameId).ToArray(); //Items in the database
            var newGameItems = viewModel.WillBringTheseGames.Where(x => !dataGameIds.Contains(x.GameId)).ToList();

            //Add new items
            newGameItems.ForEach(game =>
                {
                    var addMe = _gameRepository.GetAll().FirstOrDefault(y => y.GameId == game.GameId);

                    if (addMe != null)
                        dataModel.Games.Add(addMe);
                });
        }
        public void Get_Event_Model_State()
        {
            var model = new Event
                {
                    Title = "My title",
                    Description = "Test description",
                    Location = "My House",
                    StartDate = DateTime.Now,
                    EndDate = DateTime.Now.AddHours(3),
                    UnRegisteredInvites = new List<PendingInvitation>(),
                    RegisteredInvites = new List<Person>()
                };

            var modelState = EventService.GetSerializedModelState(model);

            Assert.AreNotEqual(modelState, string.Empty);
        }
        public void SetupSession(Event theEvent, Person thePerson)
        {
            //This is for unit testing... the http context will be null, so we skip the rest of this method
            if (System.Web.HttpContext.Current == null)
                return;

            //Reset the session manager
            SessionUtility.Events.Reset(theEvent.EventId);
            SessionUtility.Person.Reset(thePerson.PersonId);

            //Build out the list of food and games items in session
            theEvent.FoodItems.ForEach(x => SessionUtility.Events.AddFoodItem(x.FoodItemId, theEvent.EventId));
            theEvent.Games.ForEach(x => SessionUtility.Events.AddGame(x.GameId, theEvent.EventId));
            thePerson.MyFoodItems.ForEach(x => SessionUtility.Person.AddFoodItem(x.FoodItemId, thePerson.PersonId));
            thePerson.MyGames.ForEach(x => SessionUtility.Person.AddGame(x.GameId, thePerson.PersonId));
            theEvent.RegisteredInvites.ForEach(x => SessionUtility.Events.AddGuest(x.PersonId, theEvent.EventId));
            theEvent.UnRegisteredInvites.ForEach(x => SessionUtility.Events.AddGuest(-x.PendingInvitationId, theEvent.EventId)); //make sure that the id is negative!
        }
 public EditEventViewModel(Event model)
     : this()
 {
     EventId = model.EventId;
     Title = model.Title;
     Description = model.Description;
     Location = model.Location;
     StartDate = model.StartDate;
     StartTime = model.StartDate.ToString("h:mm tt");
     EndTime = model.EndDate.ToString("h:mm tt");
     if (model.FoodItems != null) model.FoodItems.ForEach(x => WillBringTheseFoodItems.Add(new FoodItemViewModel(x)));
     if (model.Games != null) model.Games.ForEach(x => WillBringTheseGames.Add(new GameViewModel(x)));
     if (model.RegisteredInvites != null) model.RegisteredInvites.ForEach(x => PeopleInvited.Add(new PersonViewModel(x)));
     if (model.UnRegisteredInvites != null) model.UnRegisteredInvites.ForEach(x =>
         {
             if (x.Email != null)
             {
                 PeopleInvited.Add(new PersonViewModel{ PersonId = -x.PendingInvitationId, FirstName = x.FirstName, LastName = x.LastName, Email = x.Email, IsRegistered = false});
             }
         });
     if (model.PeopleWhoAccepted != null) model.PeopleWhoAccepted.ForEach(x => PeopleWhoAccepted.Add(new PersonViewModel(x)));
     if (model.PeopleWhoDeclined != null) model.PeopleWhoDeclined.ForEach(x => PeopleWhoDeclined.Add(new PersonViewModel(x)));
 }
 /// <summary>
 /// Get a data model from this view model. IMPORTANT: data model date / time info not populated here!
 /// </summary>
 /// <returns></returns>
 public Event GetDataModel()
 {
     var dataModel = new Event();
     dataModel.EventId = EventId;
     dataModel.Title = Title;
     dataModel.Description = Description;
     dataModel.Location = Location;
     dataModel.RegisteredInvites = new List<Person>();
     dataModel.FoodItems = new List<FoodItem>();
     dataModel.Games = new List<Game>();
     dataModel.RegisteredInvites = new List<Person>();
     dataModel.PeopleWhoAccepted = new List<Person>();
     dataModel.PeopleWhoDeclined = new List<Person>();
     dataModel.UnRegisteredInvites = new List<PendingInvitation>();
     return dataModel;
 }
        public void Invite_New_People_By_Email()
        {
            //Arrange
            var ben = new PersonViewModel{ PersonId = -1, Email = "*****@*****.**", FirstName = "Ben", LastName = "Bufford" };
            var dan = new PersonViewModel { PersonId = -2, Email = "*****@*****.**", FirstName = "Dan", LastName = "Gidman" };
            var herb = new PersonViewModel { PersonId = -3, Email = "*****@*****.**", FirstName = "Herb", LastName = "Neese" };
            var viewModel = new EditEventViewModel { PeopleInvited = new List<PersonViewModel> { dan, herb } };
            var dataModel = new Event
            {
                Coordinator = new Person { PersonId = 1, MyUnRegisteredFriends = new List<PendingInvitation>()},
                UnRegisteredInvites = new List<PendingInvitation>
                    {
                        new PendingInvitation { PendingInvitationId = 2, Email = "*****@*****.**" },
                        new PendingInvitation { PendingInvitationId = 3, Email = "*****@*****.**" }
                    },
                RegisteredInvites = new List<Person>()
            };

            A.CallTo(() => InvitationRepo.GetAll()).Returns(new List<PendingInvitation> { new PendingInvitation
                {
                    PendingInvitationId = 1,
                    Email = "*****@*****.**"
                } }.AsQueryable());

            //Act
            viewModel.PeopleInvited.Add(ben);
            EventService.InviteNewPeople(dataModel, viewModel);

            //Assert
            Assert.AreEqual(dataModel.UnRegisteredInvites.Count, 3);
        }
        public void Index_Build_View_Model_Succeed()
        {
            //Arrange
            var eventOne = new Event {EventId = 1, Title = "Test event 1"};
            var eventTwo = new Event {EventId = 2, Title = "Test event 2"};
            var hostingEvent = new Event { EventId = 3, Title = "My own event"};
            var personResults = new List<Person>
                {
                    new Person{PersonId = 1,
                        FirstName = "Joe",
                        LastName = "Smith",
                        MyEvents = new List<Event> {hostingEvent},
                        MyInvitations = new List<Event> { eventOne, eventTwo },
                        AmAttending = new List<Event> { eventOne },
                        HaveDeclined = new List<Event> { eventTwo }
                    }
                };
            A.CallTo(() => PersonRepo.GetAll()).Returns(personResults.AsQueryable());
            A.CallTo(() => UserService.GetCurrentUserId("")).Returns(1);
            var controller = new HomeController(RepositoryFactory, UserService, NotifyService, EventService);

            //Act
            var result = controller.Index(null) as ViewResult;
            var model = result.Model as HomeViewModel;

            //Assert
            var acceptedInvitationsCount = model.MyInvitations.Count(x => x.HasAccepted == true && x.HasDeclined == false);
            var declinedInvitationsCount = model.MyInvitations.Count(x => x.HasAccepted == false && x.HasDeclined == true);
            Assert.AreEqual(string.Empty, result.ViewBag.StatusMessage);
            Assert.AreEqual(model.MyEvents.Count, 1);
            Assert.AreEqual(model.MyInvitations.Count, 2);
            Assert.AreEqual(model.HaveDeclined.Count, 1);
            Assert.AreEqual(model.AmAttending.Count, 1);
            Assert.AreEqual(acceptedInvitationsCount, 1);
            Assert.AreEqual(declinedInvitationsCount, 1);
        }
        public void RemoveGames(Event dataModel, EventBaseViewModel viewModel)
        {
            var hostGameIds = viewModel.WillBringTheseGames.Select(x => x.GameId).ToArray(); //Items in local view model
            var thePerson = _personPersonRepo.GetAll().FirstOrDefault(x => x.PersonId == viewModel.PersonId);
            var deletedGameIds = thePerson.MyGames.Where(x => !hostGameIds.Contains(x.GameId)).Select(x => x.GameId).ToList();

            //Delete items
            deletedGameIds.ForEach(id =>
            {
                var removeMe = dataModel.Games.FirstOrDefault(y => y.GameId == id);

                if (removeMe != null)
                    dataModel.Games.Remove(removeMe);
            });
        }
        public void UninvitePeople(Event dataModel, EditEventViewModel viewModel)
        {
            int parse;
            //Process peoeple with user accounts
            var modelPeopleIds = viewModel.PeopleInvited
                .Where(x => x.PersonId != 0)
                .Select(x => x.PersonId).ToArray(); //Items in local view model
            var deletedPeopleIds = dataModel.RegisteredInvites.Where(x => !modelPeopleIds.Contains(x.PersonId)).Select(x => x.PersonId).ToList();

            //Delete items
            deletedPeopleIds.ForEach(id =>
                {
                    var thePerson = _personPersonRepo.GetAll().FirstOrDefault(x => x.PersonId == id);
                    var removeInvitation = dataModel.RegisteredInvites.FirstOrDefault(y => y.PersonId == id);
                    var removeAccepted = dataModel.PeopleWhoAccepted.FirstOrDefault(y => y.PersonId == id);
                    var removeDeclined = dataModel.PeopleWhoDeclined.FirstOrDefault(y => y.PersonId == id);

                    //Remove from the invitation list
                    dataModel.RegisteredInvites.Remove(removeInvitation);

                    //Remove from the accepted list
                    if (removeAccepted != null)
                        dataModel.PeopleWhoAccepted.Remove(removeAccepted);

                    //Remove from the declined list
                    if (removeDeclined != null)
                        dataModel.PeopleWhoDeclined.Remove(removeDeclined);

                    //Remove the person's food items from the event
                    thePerson.MyFoodItems.ForEach(x =>
                        {
                            var removeMe = dataModel.FoodItems.FirstOrDefault(y => y.FoodItemId == x.FoodItemId);

                            if (removeMe != null)
                                dataModel.FoodItems.Remove(removeMe);
                        });

                    //Remove the person's games from the event
                    thePerson.MyGames.ForEach(x =>
                    {
                        var removeMe = dataModel.Games.FirstOrDefault(y => y.GameId == x.GameId);

                        if (removeMe != null)
                            dataModel.Games.Remove(removeMe);
                    });

                });

            //Process people without user accounts
            var unRegisteredIds = new List<int>();
            viewModel.PeopleInvited.Where(x => x.PersonId < 0)
                .Select(x => Math.Abs(x.PersonId)) //Note that we are making the ids posative... they are negative in the view model to keep from conflicting with registered ids
                .ToList()
                .ForEach(unRegisteredIds.Add);

            var deletedEmailInvites = dataModel.UnRegisteredInvites
                .Where(x => !unRegisteredIds.Contains(x.PendingInvitationId))
                .Select(x => x.PendingInvitationId).ToList();

            deletedEmailInvites.ForEach(pendingId =>
            {
                var removeInvitation = dataModel.UnRegisteredInvites.FirstOrDefault(y => y.PendingInvitationId == pendingId);

                //Remove from the invitation list
                dataModel.UnRegisteredInvites.Remove(removeInvitation);
            });
        }
        private EditEventViewModel GetViewModel(Event dataModel)
        {
            var model = new EditEventViewModel(dataModel);

            //Populate the total list of people who could be invited to an event.
            var userName = (User != null) ? User.Identity.Name : string.Empty;
            var userId = _userService.GetCurrentUserId(userName);
            //var people = new List<PersonViewModel>();
            var coordinator = _personRepository.GetAll().FirstOrDefault(x => x.PersonId == userId);

            model.TimeList = _eventService.GetTimeList();
            //model.FacebookFriends = _userService.GetFacebookFriends(userName);

            //Populate food and games
            if (dataModel.FoodItems != null) dataModel.FoodItems.ForEach(x => model.AllEventFoodItems.Add(new FoodItemViewModel(x)));
            if (dataModel.Games != null) dataModel.Games.ForEach(x => model.AllEventGames.Add(new GameViewModel(x)));

            model.MyFoodItems = new List<FoodItemViewModel>();
            model.MyGames = new List<GameViewModel>();

            coordinator.MyFoodItems.ForEach(x => model.MyFoodItems.Add(new FoodItemViewModel(x)));
            coordinator.MyGames.ForEach(x => model.MyGames.Add(new GameViewModel(x)));

            model.EventId = dataModel.EventId;
            model.PersonId = coordinator.PersonId;

            //Stuff the user is already bringing
            if (dataModel.FoodItems != null)
            {
                var eventFoodItemIds = dataModel.FoodItems.Select(x => x.FoodItemId);
                var hostFoodItemIds = coordinator.MyFoodItems.Select(x => x.FoodItemId);
                var selectedFoodItems = hostFoodItemIds.Intersect(eventFoodItemIds);
                model.WillBringTheseFoodItems = dataModel.FoodItems
                    .Where(x => selectedFoodItems.Contains(x.FoodItemId))
                    .Select(x => new FoodItemViewModel(x)).ToList();
                model.WillBringTheseFoodItems.ForEach(x =>
                    {
                        x.EventId = model.EventId;
                        x.Index = model.WillBringTheseFoodItems.IndexOf(x);
                });
            }

            if (dataModel.Games != null)
            {
                var eventGameIds = dataModel.Games.Select(x => x.GameId);
                var hostGameIds = coordinator.MyGames.Select(x => x.GameId);
                var selectedGames = hostGameIds.Intersect(eventGameIds);
                model.WillBringTheseGames =
                    dataModel.Games.Where(x => selectedGames.Contains(x.GameId)).Select(x => new GameViewModel(x)).ToList();
                model.WillBringTheseGames.ForEach(x =>
                {
                    x.EventId = model.EventId;
                    x.Index = model.WillBringTheseGames.IndexOf(x);
                });
            }

            model.PersonId = coordinator.PersonId;

            return model;
        }
        public string GetSerializedModelState(Event dataModel)
        {
            var modelState =
                new
                {
                    dataModel.Title,
                    dataModel.Description,
                    dataModel.Location,
                    dataModel.StartDate
                };

            return JsonConvert.SerializeObject(modelState);
        }
        /// <summary>
        /// Get an event by the specified event id
        /// </summary>
        /// <param name="eventId">An event id</param>
        /// <returns></returns>
        private Event GetEventById(int eventId)
        {
            var theEvent = _eventRepository.GetAll().FirstOrDefault(x => x.EventId == eventId);

            if (theEvent == null)
            {
                theEvent = new Event
                    {
                        RegisteredInvites = new List<Person>(),
                        UnRegisteredInvites = new List<PendingInvitation>(),
                        PeopleWhoAccepted = new List<Person>(),
                        PeopleWhoDeclined = new List<Person>()
                    };
            }

            return theEvent;
        }
        /// <summary>
        /// Get a new instance of the edit event view model with the accepted and declined attendee lists populated
        /// </summary>
        /// <param name="theEvent">An event</param>
        /// <returns></returns>
        private EditEventViewModel GetEventViewModel(Event theEvent)
        {
            var viewModel = new EditEventViewModel();
            viewModel.EventId = theEvent.EventId;
            theEvent.PeopleWhoAccepted.ForEach(x => viewModel.PeopleWhoAccepted.Add(new PersonViewModel(x)));
            theEvent.PeopleWhoDeclined.ForEach(x => viewModel.PeopleWhoDeclined.Add(new PersonViewModel(x)));

            return viewModel;
        }
        public void Invite_New_People()
        {
            //Arrange
            var personOne = new PersonViewModel{PersonId = 1};
            var personTwo = new PersonViewModel { PersonId = 2 };
            var personThree = new PersonViewModel { PersonId = 3 };
            var theHost = new Person { PersonId = 4, MyRegisteredFriends = new List<Person>(), MyUnRegisteredFriends = new List<PendingInvitation>()};
            var viewModel = new EditEventViewModel{ PeopleInvited = new List<PersonViewModel>{personTwo, personThree} };
            var dataModel = new Event
                {
                    Coordinator = theHost,
                    RegisteredInvites = new List<Person> {new Person{PersonId = 2}, new Person{PersonId = 3}},
                    UnRegisteredInvites = new List<PendingInvitation>()
                };

            A.CallTo(() => PersonRepo.GetAll()).Returns(new List<Person> { new Person() { PersonId = 1 } }.AsQueryable());

            //Act
            viewModel.PeopleInvited.Add(personOne);
            EventService.InviteNewPeople(dataModel, viewModel);

            //Assert
            Assert.AreEqual(dataModel.RegisteredInvites.Count, 3);
        }
        public void Uninvite_People()
        {
            //Arrange
            var personOne = new Person { PersonId = 1, MyFoodItems = new List<FoodItem>(), MyGames = new List<Game>()};
            var personTwo = new Person { PersonId = 2, MyFoodItems = new List<FoodItem>(), MyGames = new List<Game>() };
            var personThree = new Person { PersonId = 3, MyFoodItems = new List<FoodItem>(), MyGames = new List<Game>() };

            var vmPersonOne = new PersonViewModel(personOne);
            var vmPersonTwo = new PersonViewModel(personTwo);
            var vmEmailPerson = new PersonViewModel { PersonId = -3, Email = "*****@*****.**" };

            var viewModel = new EditEventViewModel { PeopleInvited = new List<PersonViewModel>
                {
                    vmPersonOne,
                    vmPersonTwo,
                    vmEmailPerson
                } };
            var dataModel = new Event
            {
                RegisteredInvites = new List<Person> { new Person { PersonId = 2 }, new Person { PersonId = 3 } },
                UnRegisteredInvites = new List<PendingInvitation> { new PendingInvitation { PendingInvitationId = 3, Email = "*****@*****.**" } },
                PeopleWhoAccepted = new List<Person> { new Person { PersonId = 2 } },
                PeopleWhoDeclined = new List<Person> { new Person { PersonId = 3 } }
            };

            A.CallTo(() => PersonRepo.GetAll()).Returns(new EnumerableQuery<Person>(new[] {personOne, personTwo, personThree}));

            //Act
            viewModel.PeopleInvited.Remove(vmPersonOne);
            viewModel.PeopleInvited.Remove(vmPersonTwo);
            viewModel.PeopleInvited.Remove(vmEmailPerson);
            EventService.UninvitePeople(dataModel, viewModel);

            //Assert
            Assert.AreEqual(dataModel.RegisteredInvites.Count, 0);
            Assert.AreEqual(dataModel.UnRegisteredInvites.Count, 0);
            Assert.AreEqual(dataModel.PeopleWhoAccepted.Count, 0);
            Assert.AreEqual(dataModel.PeopleWhoDeclined.Count, 0);
        }
        public void Remove_Games()
        {
            //Arrange
            var settlers = new Game { GameId = 1, Title = "Settlers" };
            var shadows = new Game { GameId = 2, Title = "Shadows" };
            var heros = new Game { GameId = 3, Title = "Heros" };
            var monopoly = new Game { GameId = 4, Title = "Monopoly" };

            var model = new EventBaseViewModel
            {
                AllEventGames = new List<GameViewModel>
                    {
                        new GameViewModel(settlers),
                        new GameViewModel(shadows),
                        new GameViewModel(heros),
                        new GameViewModel(monopoly)
                    },
                WillBringTheseGames = new List<GameViewModel>(new[] { new GameViewModel(monopoly),  }), // this is what the user is bringing
            };

            //These are in the database
            var dataModel = new Event
            {
                Coordinator = new Person { MyGames = new List<Game> { shadows, monopoly } },
                Games = new List<Game> { settlers, shadows, heros, monopoly}
            };

            A.CallTo(() => PersonRepo.GetAll()).Returns(new List<Person>(new[] { dataModel.Coordinator }).AsQueryable());

            //Act
            EventService.RemoveGames(dataModel, model);

            //Assert
            Assert.AreEqual(dataModel.Games.Count, 3); //only the candy is removed.
        }
        private InvitationDetailsViewModel GetViewModel(Event theEvent, Person thePerson)
        {
            var model = new InvitationDetailsViewModel { EventId = theEvent.EventId,
                Title = theEvent.Title,
                Description = theEvent.Description,
                PersonId = thePerson.PersonId,
                StartDate = theEvent.StartDate,
                StartTime = theEvent.StartDate.ToString("h:mm tt"),
                EndTime = theEvent.EndDate.ToString("h:mm tt"),
                PeopleInvited = new List<PersonViewModel>()
            };

            PopulateFoodAndGames(theEvent, thePerson, model);

            model.Coordinator = new PersonViewModel(theEvent.Coordinator);
            model.EventLocation = theEvent.Location;

            //Stuff the user is already bringing
            var eventFoodItemIds = theEvent.FoodItems.Select(x => x.FoodItemId);
            var personFoodItemIds = thePerson.MyFoodItems.Select(x => x.FoodItemId);
            var selectedFoodItems = personFoodItemIds.Intersect(eventFoodItemIds);
            model.WillBringTheseFoodItems =
                theEvent.FoodItems.Where(x => selectedFoodItems.Contains(x.FoodItemId)).Select(x => new FoodItemViewModel(x)).ToList();

            //Populate the event id for each item
            model.WillBringTheseFoodItems.ForEach(x => x.EventId = theEvent.EventId);

            var eventGameIds = theEvent.Games.Select(x => x.GameId);
            var personGameIds = thePerson.MyGames.Select(x => x.GameId);
            var selectedGames = personGameIds.Intersect(eventGameIds);
            model.WillBringTheseGames =
                theEvent.Games.Where(x => selectedGames.Contains(x.GameId)).Select(x => new GameViewModel(x)).ToList();

            //Populate the event id for each item
            model.WillBringTheseGames.ForEach(x => x.EventId = theEvent.EventId);

            //People who are coming
            theEvent.RegisteredInvites.ForEach(x => model.PeopleInvited.Add(new PersonViewModel(x)));
            theEvent.UnRegisteredInvites.ForEach(x => model.PeopleInvited.Add(new PersonViewModel
                {
                    FirstName = x.FirstName,
                    LastName = x.LastName
                }));

            //Order by first name, last name
            model.PeopleInvited = model.PeopleInvited
                .OrderBy(x => x.FirstName)
                .ThenBy(x => x.LastName).ToList();

            return model;
        }
        public void Edit_Event_Fail()
        {
            //Arrange
            var theHost = new Person
                {
                    PersonId = 0,
                    FirstName = "Billy",
                    LastName = "Bob",
                    MyFoodItems = new List<FoodItem>(),
                    MyGames = new List<Game>()
                };
            var theEvent = new Event {
                EventId = 1,
                Coordinator = theHost,
                Title = "My Event",
                Description = "It's cool",
                Location = "My House",
                StartDate = DateTime.Now,
                RegisteredInvites = new List<Person>(),
                UnRegisteredInvites = new List<PendingInvitation>(),
                FoodItems = new List<FoodItem>(),
                Games = new List<Game>()
            };
            var viewModel = new EditEventViewModel(theEvent);
            var contoller = new EventController(RepositoryFactory, EventService, UserService, NotifyService);

            //Act
            A.CallTo(() => EventRepo.GetAll()).Returns(new List<Event> { theEvent }.AsQueryable());
            A.CallTo(() => PersonRepo.GetAll()).Returns(new List<Person> { theHost }.AsQueryable());
            A.CallTo(() => EventRepo.SubmitChanges()).Throws(new Exception("Crap I crashed."));
            var result = contoller.Edit(viewModel) as ViewResult;

            //Assert
            Assert.AreEqual(result.ViewBag.StatusMessage, Constants.BASE_SAVE_FAIL);
        }
        private void PopulateFoodAndGames(Event theEvent, Person thePerson, InvitationDetailsViewModel model)
        {
            //Populate the games and food that are already coming
            theEvent.FoodItems.ForEach(x => model.AllEventFoodItems.Add(new FoodItemViewModel(x)));
            theEvent.Games.ForEach(x => model.AllEventGames.Add(new GameViewModel(x)));

            //Populate all of the food items and games owned by the person
            var foodItems = new List<SelectListItem>();
            var games = new List<SelectListItem>();

            thePerson.MyFoodItems
                             .ToList()
                             .ForEach(
                                 x => foodItems.Add(new SelectListItem
                                 {
                                     Value = x.FoodItemId.ToString(),
                                     Text = x.Title
                                 }));

            thePerson.MyGames
                             .ToList()
                             .ForEach(
                                 x => games.Add(new SelectListItem
                                 {
                                     Value = x.GameId.ToString(),
                                     Text = x.Title
                                 }));

            model.MyFoodItems = new MultiSelectList(foodItems, "Value", "Text");
            model.MyGames = new MultiSelectList(games, "Value", "Text");
        }
        /// <summary>
        /// Send invitations to newly invited people
        /// </summary>
        /// <param name="theEvent">The specified event</param>
        /// <param name="registeredInvites">A list of newly invited people who are registered users</param>
        /// <param name="nonRegisteredInvites">A list of newly invited people who are non-registered users</param>
        private void SendInvitations(Event theEvent, List<Person> registeredInvites, List<PendingInvitation> nonRegisteredInvites)
        {
            //This is here so that unit tests on this controller will pass.
            if (Request == null)
                return;

            var notifications = new List<EventPlannerNotification>();

            registeredInvites.ForEach(x =>
            {
                var notificationUrl = string.Format("{0}://{1}{2}",
                    Request.Url.Scheme,
                    Request.Url.Authority,
                    Url.Action("AcceptInvitation", "Home", new { eventId = theEvent.EventId, accepteeId = x.PersonId }));
                var notification = _notificationService
                    .GetNewInvitationNotification(theEvent.EventId, x.PersonId, 0, notificationUrl);

                notifications.Add(notification);
            });

            nonRegisteredInvites.ForEach(x =>
            {
                var notificationUrl = string.Format("{0}://{1}{2}",
                    Request.Url.Scheme,
                    Request.Url.Authority,
                    Url.Action("Register", "Account", new { eventId = theEvent.EventId, pendingInvitationId = x.PendingInvitationId }));

                var notification = _notificationService
                    .GetNewInvitationNotification(theEvent.EventId, 0, x.PendingInvitationId, notificationUrl);

                notifications.Add(notification);
            });

            _notificationService.SendNotifications(notifications);
        }
        public void InviteNewPeople(Event dataModel, EditEventViewModel viewModel)
        {
            int tParse;

            //Add the temp user ids to the pending invitations table
            var emailList = new List<string>();
            var facebookIdList = new List<string>();
            var emailInvites = viewModel.PeopleInvited.Where(x => x.PersonId < 0).ToList();
            //var facebookInvites = viewModel.PeopleInvited.Where(x => x.Split(delimiter).Length == 2).ToList();

            emailInvites.ForEach(x =>
                {
                    var emailAddress = x.Email;
                    emailList.Add(emailAddress);

                    //Make sure it doesn't exist already
                    var exists = _invitationRepository.GetAll().FirstOrDefault(y => y.Email == emailAddress);

                    if (exists == null)
                    {
                        var emailInvite = new PendingInvitation
                        {
                            PersonId = dataModel.Coordinator.PersonId,
                            Email = emailAddress,
                            FirstName = x.FirstName,
                            LastName = x.LastName
                        };

                        _invitationRepository.Insert(emailInvite);
                    }
                });

            //facebookInvites.ForEach(x =>
            //{
            //    var tempUserArray = x.Split(delimiter);
            //    var facebookId = tempUserArray[0];

            //    //Get the first and last name values
            //    var nameArray = tempUserArray[1].Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
            //    var firstName = nameArray[0];
            //    var lastName = nameArray[nameArray.Length - 1];

            //    facebookIdList.Add(facebookId);

            //    //Make sure it doesn't exist already
            //    var exists = _invitationRepository.GetAll().FirstOrDefault(y => y.FacebookId == facebookId);

            //    if (exists == null)
            //    {
            //        var facebookInvite = new PendingInvitation
            //        {
            //            PersonId = dataModel.Coordinator.PersonId,
            //            FacebookId = facebookId,
            //            FirstName = firstName,
            //            LastName = lastName
            //        };

            //        _invitationRepository.Insert(facebookInvite);
            //    }
            //});

            _invitationRepository.SubmitChanges();

            //Find the existing user ids
            var dataPeopleIds = dataModel.RegisteredInvites.Select(x => x.PersonId).ToArray(); //Items in the database
            var newPeople = viewModel.PeopleInvited
                .Where(x => x.PersonId > 0)
                .Where(x => !dataPeopleIds.Contains(x.PersonId)).ToList();

            //Add new people
            newPeople.ForEach(person =>
                {
                    var inviteMe = _personPersonRepo.GetAll().FirstOrDefault(x => x.PersonId == person.PersonId);

                    if (inviteMe != null)
                    {
                        dataModel.RegisteredInvites.Add(inviteMe);

                        //Add the new invite to the user's list of friends if necissary...
                        var exists =
                            dataModel.Coordinator.MyRegisteredFriends.FirstOrDefault(
                                x => x.PersonId == inviteMe.PersonId);

                        if (exists == null)
                        {
                            dataModel.Coordinator.MyRegisteredFriends.Add(inviteMe);
                        }
                    }
                });

            //Find the existing temp emails
            var emailPeople = dataModel.UnRegisteredInvites.Where(x => emailList.Contains(x.Email))
                .Select(x => x.Email).ToArray(); //Items in the database
            var newEmailPeople = emailList
                .Where(x => !emailPeople.Contains(x)).ToList();

            //Add people invited by email
            newEmailPeople.ForEach(email =>
            {
                var inviteMe = _invitationRepository.GetAll().FirstOrDefault(invite => invite.Email == email);

                if (inviteMe != null)
                {
                    dataModel.UnRegisteredInvites.Add(inviteMe);

                    //Add the new email invite to the user's list of friends if necissary...
                    var exists =
                        dataModel.Coordinator.MyUnRegisteredFriends.FirstOrDefault(
                            x => x.PendingInvitationId == inviteMe.PendingInvitationId);

                    if (exists == null)
                    {
                        dataModel.Coordinator.MyUnRegisteredFriends.Add(inviteMe);
                    }
                }
            });

            //Find the existing temp facebook ids
            var facebookPeople = dataModel.UnRegisteredInvites.Where(x => facebookIdList.Contains(x.FacebookId))
                .Select(x => x.FacebookId).ToArray(); //Items in the database
            var newFacebookPeople = facebookIdList
                .Where(x => !facebookPeople.Contains(x)).ToList();

            //Add new people invited by facebook
            newFacebookPeople.ForEach(facebookId =>
            {
                var inviteMe = _invitationRepository.GetAll().FirstOrDefault(invite => invite.FacebookId == facebookId);

                if (inviteMe != null)
                {
                    dataModel.UnRegisteredInvites.Add(inviteMe);

                    //Add the new facebook invite to the user's list of friends if necissary...
                    var exists =
                        dataModel.Coordinator.MyUnRegisteredFriends.FirstOrDefault(
                            x => x.PendingInvitationId == inviteMe.PendingInvitationId);

                    if (exists == null)
                    {
                        dataModel.Coordinator.MyUnRegisteredFriends.Add(inviteMe);
                    }
                }
            });
        }
        /// <summary>
        /// Send un-invitations 
        /// </summary>
        /// <param name="theEvent">The specified event</param>
        /// <param name="registeredInvites">A list of newly un-invited people who are registered users</param>
        /// <param name="nonRegisteredInvites">A list of newly un-invited people who are non-registered users</param>
        private void SendUnInvitations(Event theEvent, List<Person> registeredInvites, List<PendingInvitation> nonRegisteredInvites)
        {
            //This is here so that unit tests on this controller will pass.
            if (Request == null)
                return;

            var notifications = new List<EventPlannerNotification>();

            registeredInvites.ForEach(x =>
            {
                var notification = _notificationService
                    .GetPersonRemovedFromEventNotification(theEvent.EventId, x.PersonId, 0);

                notifications.Add(notification);
            });

            nonRegisteredInvites.ForEach(x =>
            {
                var notification = _notificationService
                    .GetPersonRemovedFromEventNotification(theEvent.EventId, 0, x.PendingInvitationId);

                notifications.Add(notification);
            });

            _notificationService.SendNotifications(notifications);
        }
        public void SetEventDates(Event dataModel, EditEventViewModel viewModel)
        {
            DateTime startTime =
                DateTime.Parse(viewModel.StartDate.Value.ToShortDateString() + " " + viewModel.StartTime);
            DateTime endTime =
                DateTime.Parse(viewModel.StartDate.Value.ToShortDateString() + " " + viewModel.EndTime);

            int hours = startTime.Hour;
            int minutes = startTime.Minute;

            //Set the data model start date...
            dataModel.StartDate = viewModel.StartDate.Value.Date.AddHours(hours).AddMinutes(minutes);

            int endHour = endTime.Hour;
            int endMinute = endTime.Minute;
            dataModel.EndDate = dataModel.StartDate.Date.AddHours(endHour).AddMinutes(endMinute);

            //Change the end date if...
            if (dataModel.StartDate.Hour > endTime.Hour)
                dataModel.EndDate = dataModel.StartDate.Date.AddDays(1).Date.AddHours(endHour).AddMinutes(endMinute);
        }
        /// <summary>
        /// Send update notifications to everyone who was invited.
        /// </summary>
        /// <param name="theEvent">The specified event</param>
        /// <param name="newRegisteredInvites">A list of newly invited people who are registered users</param>
        /// <param name="newNonRegisteredInvites">A list of newly invited people who are non-registered users</param>
        private void SendUpdateNotifications(Event theEvent, List<Person> newRegisteredInvites, List<PendingInvitation> newNonRegisteredInvites)
        {
            //This is here so that unit tests on this controller will pass. So much easier than faking it!
            if (Request == null)
                return;

            var notifications = new List<EventPlannerNotification>();

            //Only send update notification to people who have already been invited
            theEvent.RegisteredInvites
                .Where(x => !newRegisteredInvites.Select(y => y.PersonId).Contains(x.PersonId))
                .ToList().ForEach(x =>
            {
                var updateNotification = _notificationService.GetNotificationForEventUpdate(theEvent.EventId, x.PersonId, 0);
                notifications.Add(updateNotification);
            });

            theEvent.UnRegisteredInvites
                .Where(x => !newNonRegisteredInvites.Select(y => y.PendingInvitationId).Contains(x.PendingInvitationId))
                .ToList().ForEach(x =>
            {
                var updateNotification = _notificationService.GetNotificationForEventUpdate(theEvent.EventId, 0, x.PendingInvitationId);
                notifications.Add(updateNotification);
            });

            _notificationService.SendNotifications(notifications);

            //Invite new people to the event...
            SendInvitations(theEvent, newRegisteredInvites, newNonRegisteredInvites);
        }
        /// <summary>
        /// Send out notifications indicating that an event has been cancelled.
        /// </summary>
        /// <param name="theEvent">The specified event</param>
        private void SendCancellationNotifications(Event theEvent)
        {
            //This is here so that unit tests on this controller will pass. So much easier than faking it!
            if (Request == null)
                return;

            var notifications = new List<EventPlannerNotification>();

            //Only send update notification to people who have already been invited
            theEvent.RegisteredInvites.ForEach(x =>
                {
                    var updateNotification = _notificationService.GetNotificationForEventCancelled(theEvent.EventId, x.PersonId, 0);
                    notifications.Add(updateNotification);
                });

            theEvent.UnRegisteredInvites.ForEach(x =>
                {
                    var updateNotification = _notificationService.GetNotificationForEventCancelled(theEvent.EventId, 0, x.PendingInvitationId);
                    notifications.Add(updateNotification);
                });

            _notificationService.SendNotifications(notifications);
        }
        public void Parse_Event_Dates()
        {
            //Arrange
            var hours = 4;
            var startTimeValue = "4:00 AM"; //today
            var endTimeValue = "2:30 AM"; //This SHOULD be 2AM the next day...
            var dataModel = new Event();
            var viewModel = new EditEventViewModel { StartDate = DateTime.Now, StartTime = startTimeValue, EndTime = endTimeValue };

            //Act
            EventService.SetEventDates(dataModel, viewModel);

            //Assert
            Assert.AreEqual(dataModel.StartDate, DateTime.Now.Date.AddHours(4));
            Assert.AreEqual(dataModel.EndDate, DateTime.Now.Date.AddHours(26).AddMinutes(30));
        }