using Fest.WebClient.Models;
using Microsoft.AspNetCore.Mvc;
using System.Net;

namespace Fest.WebClient.Controllers
{
    public class HomeController : Controller
    {
        private readonly IConfiguration _configuration;
        private readonly HttpClient _httpClient;

        public HomeController(IConfiguration configuration, HttpClient httpClient)
        {
            _configuration = configuration;
            _httpClient = httpClient;
        }

        public async Task<IActionResult> Index()
        {
            if (Request.Method == "POST")
            {
                string? zip = Request.Form["zip"];
                if (zip != null)
                {
                    ViewBag.Zip = zip;
                    var result = await GetWeatherAsync(zip);
                    if (result != null)
                        ViewBag.Result = result;
                    else
                        ViewBag.ErrorMessage = $"No weather data by ZIP {zip}";
                }
                else
                    ViewBag.ErrorMessage = "No ZIP given";
            }

            return View();
        }

        [Route("history")]
        public async Task<IActionResult> History()
        {
            var model = new HistoryModel
            {
                Items = await GetRequestsHistoryAsync()
            };

            return View(model);
        }

        [Route("docs")]
        public IActionResult Docs()
        {
            return View();
        }

        #region private

        private async Task<CityTemperature?> GetWeatherAsync(string zip)
        {
            var request = new HttpRequestMessage()
            {
                RequestUri = new Uri($"{_configuration["WebApiHost"]}/weather/{zip}"),
                Method = HttpMethod.Get
            };

            request.Headers.Add("X-Client-Id", HttpContext.Session.GetXClientId());

            var response = await _httpClient.SendAsync(request);
            return response.StatusCode == HttpStatusCode.OK
                ? await response.Content.ReadFromJsonAsync<CityTemperature>()
                : null;
        }

        private async Task<List<CityTemperature>?> GetRequestsHistoryAsync()
        {
            var request = new HttpRequestMessage()
            {
                RequestUri = new Uri($"{_configuration["WebApiHost"]}/weather/history"),
                Method = HttpMethod.Get
            };

            request.Headers.Add("X-Client-Id", HttpContext.Session.GetXClientId());

            var response = await _httpClient.SendAsync(request);
            return response.StatusCode == HttpStatusCode.OK
                ? await response.Content.ReadFromJsonAsync<List<CityTemperature>>()
                : null;
        }

        #endregion
    }
}