using ConstructorAppUI.Dtos.HomeBannerDtos;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Text;

namespace ConstructorAppUI.Controllers
{
    public class HomeBannerController : Controller
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly string _apiBaseUrl;

        public HomeBannerController(IHttpClientFactory httpClientFactory, IWebHostEnvironment webHostEnvironment, IConfiguration configuration)
        {
            _httpClientFactory = httpClientFactory;
            _webHostEnvironment = webHostEnvironment;
            _apiBaseUrl = configuration["ApiSettings:BaseUrl"];
        }

        public async Task<IActionResult> Index()
        {
            var client = _httpClientFactory.CreateClient();
            var responseMessage = await client.GetAsync($"{_apiBaseUrl}/api/HomeBanner");
            if (responseMessage.IsSuccessStatusCode)
            {
                var jsonData = await responseMessage.Content.ReadAsStringAsync();
                var values = JsonConvert.DeserializeObject<List<ResultHomeBannerDto>>(jsonData);
                return View(values);
            }
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> UpdateHomeBanner(int id)
        {
            var client = _httpClientFactory.CreateClient();
            var responseMessage = await client.GetAsync($"{_apiBaseUrl}/api/HomeBanner/{id}");
            if (responseMessage.IsSuccessStatusCode)
            {
                var jsonData = await responseMessage.Content.ReadAsStringAsync();
                var values = JsonConvert.DeserializeObject<UpdateHomeBannerDto>(jsonData);
                return View(values);
            }
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> UpdateHomeBanner(UpdateHomeBannerDto updateHomeBannerDto, IFormFile ImageFile)
        {
            var client = _httpClientFactory.CreateClient();

            // Mevcut "Slider" verisini al
            var existingSliderResponse = await client.GetAsync($"{_apiBaseUrl}/api/HomeBanner/{updateHomeBannerDto.HomeBannerID}");
            if (existingSliderResponse.IsSuccessStatusCode)
            {
                var existingJsonData = await existingSliderResponse.Content.ReadAsStringAsync();
                var existingSlider = JsonConvert.DeserializeObject<UpdateHomeBannerDto>(existingJsonData);

                // Görseller için "wwwroot/Images" klasörünün varlığını kontrol et
                var imagesPath = Path.Combine(_webHostEnvironment.WebRootPath, "Images");
                if (!Directory.Exists(imagesPath))
                {
                    Directory.CreateDirectory(imagesPath);
                }

                // LogoUrl için işlem
                if (ImageFile != null && ImageFile.Length > 0)
                {
                    // Eski görseli sil
                    if (!string.IsNullOrEmpty(existingSlider.LogoUrl))
                    {
                        var oldImagePath = Path.Combine(_webHostEnvironment.WebRootPath, existingSlider.LogoUrl.TrimStart('/'));
                        if (System.IO.File.Exists(oldImagePath))
                        {
                            System.IO.File.Delete(oldImagePath);
                        }
                    }

                    // Yeni görseli yükle
                    var fileName = Path.GetFileName(ImageFile.FileName);
                    var imagePath = Path.Combine(imagesPath, fileName);
                    using (var stream = new FileStream(imagePath, FileMode.Create))
                    {
                        await ImageFile.CopyToAsync(stream);
                    }
                    updateHomeBannerDto.LogoUrl = $"/Images/{fileName}";
                }
                else
                {
                    updateHomeBannerDto.LogoUrl = existingSlider.LogoUrl;
                }

                // API'ye güncelleme isteği gönder
                var updatedJsonData = JsonConvert.SerializeObject(updateHomeBannerDto);
                StringContent stringContent = new StringContent(updatedJsonData, Encoding.UTF8, "application/json");
                var responseMessage = await client.PutAsync($"{_apiBaseUrl}/api/HomeBanner/", stringContent);
                if (responseMessage.IsSuccessStatusCode)
                {
                    return RedirectToAction("Index");
                }
            }

            return View(updateHomeBannerDto);
        }
    }
}
