using ChatMvc.Managers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http.Headers;
using static System.Net.Mime.MediaTypeNames;

namespace ChatMvc.Controllers
{
    [Authorize]
    public class DocumentsController : Controller
    {
        private readonly HttpClient _httpClient;
        private readonly TokenManager _tokenManager;

        public DocumentsController(TokenManager tokenManager)
        {
            _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri("http://localhost:5020/");
            this._tokenManager = tokenManager;
        }

        public async Task<IActionResult> Index()
        {
            var token = User.Claims.FirstOrDefault(f => f.Type == "TokenExternal").Value;

            if (_tokenManager.IsTokenExpired(token)) {
                var userId = User.Claims.FirstOrDefault(f => f.Type == "TokenExternal").Value;
                token = await _tokenManager.GetToken(User);
            }

            _httpClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));

            var response = await _httpClient.GetAsync("Chat/texts");
            if (response.IsSuccessStatusCode)
            {
                var texts = await response.Content.ReadFromJsonAsync<IEnumerable<TextResponse>>();
                return View(texts);
            }
            return View(new List<TextResponse>());
        }

        public IActionResult New()
        {
            return View();
        }

        public async Task<IActionResult> Edit(string id)
        {
            var token = User.Claims.FirstOrDefault(f => f.Type == "TokenExternal").Value;

            _httpClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));

            var response = await _httpClient.GetAsync(string.Format("chat/texts/id/{0}", id));
            if (response.IsSuccessStatusCode)
            {
                var text = await response.Content.ReadFromJsonAsync<TextResponse>();
                var request = new TextRequest()
                {
                    Id = text.Id,
                    Title = text.Title,
                    Content = text.Content
                };
                return View("New", request);
            }
            return View("New");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Save([FromForm] TextRequest request)
        {
            var token = User.Claims.FirstOrDefault(f => f.Type == "TokenExternal").Value;

            _httpClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));

            var response = await _httpClient.PostAsJsonAsync("chat/savetext", request);
            if (response.IsSuccessStatusCode)
            {
                return RedirectToAction("Index");
            }
            return View("Novo", request);
        }
    }

    public class TextResponse
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
    }

    public class TextRequest
    {
        public string? Id { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
    }
}

