Example #1
0
        public async Task <IActionResult> CreateJogging([FromBody] JoggingCreateDto joggingCreateDto)
        {
            var claimsIdentity = this.User.Identity as ClaimsIdentity;
            var userName       = claimsIdentity.FindFirst(ClaimTypes.Name)?.Value;
            var role           = claimsIdentity.FindFirst(ClaimTypes.Role)?.Value;
            var user           = _userManager.Users.Where(u => u.Id.Equals(joggingCreateDto.UserId)).FirstOrDefault();

            if (user == null)
            {
                ModelState.AddModelError("", $"User with userid: {joggingCreateDto.UserId} does not exist");
                return(BadRequest(ModelState));
            }
            if (user.UserName != userName && role != "Admin")
            {
                return(StatusCode(403));
            }

            var searchDate = joggingCreateDto.JoggingDate;
            var jogging    = _mapper.Map <Jogging>(joggingCreateDto);
            WeatherServiceResult weatherResult;

            if (searchDate < DateTime.Today)
            {
                weatherResult = await _weatherManager.GetHistoryWeather(joggingCreateDto.Location, searchDate);
            }
            else
            {
                weatherResult = await _weatherManager.GetCurrentOrForecast(joggingCreateDto.Location, searchDate);
            }

            if (weatherResult != null && weatherResult.Succeeded)
            {
                jogging.TemperatureC     = weatherResult.TempC;
                jogging.TemperatureF     = weatherResult.TempF;
                jogging.WeatherCondition = weatherResult.WeatherCondition;
                jogging.humidity         = weatherResult.Humidity;
                jogging.DateCreated      = DateTime.Now;
                jogging.DateUpdated      = DateTime.Now;

                _repo.CreateJogging(jogging);
                _repo.Save();

                var joggingToReturn = _mapper.Map <JoggingDto>(jogging);
                return(CreatedAtRoute("GetJoggingById", new { id = joggingToReturn.Id }, joggingToReturn));
            }
            else
            {
                return(StatusCode(422, new { Success = false, weatherResult.ErrorMessage }));
            }
        }