public async Task <IActionResult> Finish(string macAddress) { var currentGame = await _attemptRepository.GetLastAsync(); var currentDevice = await _deviceRepository.GetAsync(x => x.MacAddress == macAddress); if (currentGame == null || currentDevice.Id == 0) { return(NoContent()); } // Finish device var attemptDevice = currentGame.AttemptDevices.FirstOrDefault(x => x.DeviceId == currentDevice.Id); if (attemptDevice == null || attemptDevice.AttemptId == 0) { return(NoContent()); } attemptDevice.FinishedAt = DateTime.Now; await _attemptDeviceRepository.UpdateAsync(attemptDevice); // Fetch all devices on the same order that this device is trying to finish var devicesInOrder = (await _deviceRepository.GetListAsync(x => x.Order == currentDevice.Order)) .Select(x => x.Id).ToList(); // Get all the devices that are finished on this order in this attempt var attemptDevicesFinished = await _attemptDeviceRepository.GetListAsync(x => devicesInOrder.Contains(x.DeviceId) && x.FinishedAt != null && x.AttemptId == currentGame.Id); // Everything is finished on this order, either finish the game or start the next order if (devicesInOrder.Count == attemptDevicesFinished.Count) { var devices = await _deviceRepository.GetListAsync(x => x.Order == currentDevice.Order + 1); // If there are no devices in the next order, meaning there are no devices to be completed, finish the game if (devices.Count == 0) { attemptDevice.Attempt.EndDate = DateTime.Now; await _attemptRepository.UpdateAsync(attemptDevice.Attempt); return(Ok(JsonHelper.FixCycle(attemptDevice.Attempt))); } // Are there devices that have to start after the current order? Start them here foreach (var nextDevice in devices) { await _attemptDeviceRepository.AddAsync(new AttemptDevice { AttemptId = attemptDevice.Attempt.Id, DeviceId = nextDevice.Id, StartedAt = DateTime.Now }); } } return(Ok(JsonHelper.FixCycle(attemptDevice.Attempt))); }
public async Task <IActionResult> Start() { var attempt = await _attemptRepository.AddAsync(new Attempt { StartDate = DateTime.Now }); var devices = await _deviceRepository.GetListAsync(); if (devices.Count == 0) { return(NoContent()); } var orderNumber = devices.OrderBy(x => x.Order).First().Order; foreach (var device in devices.Where(x => x.Order == orderNumber)) { await _attemptDeviceRepository.AddAsync(new AttemptDevice { AttemptId = attempt.Id, DeviceId = device.Id, StartedAt = DateTime.Now }); } return(Ok(JsonHelper.FixCycle(attempt))); }