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

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

        public WorkProcessController(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/WorkProcess");
            if (responseMessage.IsSuccessStatusCode)
            {
                var jsonData = await responseMessage.Content.ReadAsStringAsync();
                var values = JsonConvert.DeserializeObject<List<ResultWorkProcessDto>>(jsonData);
                return View(values);
            }
            return View();
        }

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

        [HttpPost]
        public async Task<IActionResult> UpdateWorkProcess(UpdateWorkProcessDto updateWorkProcessDto, IFormFile ImageFile)
        {
            var client = _httpClientFactory.CreateClient();

            // Mevcut "WorkProcess" verisini al
            var existingSliderResponse = await client.GetAsync($"{_apiBaseUrl}/api/WorkProcess/{updateWorkProcessDto.WorkProcessID}");
            if (existingSliderResponse.IsSuccessStatusCode)
            {
                var existingJsonData = await existingSliderResponse.Content.ReadAsStringAsync();
                var existingSlider = JsonConvert.DeserializeObject<UpdateWorkProcessDto>(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);
                }

                // ImageUrl için işlem
                if (ImageFile != null && ImageFile.Length > 0)
                {
                    // Eski görseli sil
                    if (!string.IsNullOrEmpty(existingSlider.ImageUrl))
                    {
                        var oldImagePath = Path.Combine(_webHostEnvironment.WebRootPath, existingSlider.ImageUrl.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);
                    }
                    updateWorkProcessDto.ImageUrl = $"/Images/{fileName}";
                }
                else
                {
                    updateWorkProcessDto.ImageUrl = existingSlider.ImageUrl;
                }

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

            return View(updateWorkProcessDto);
        }

        public async Task<IActionResult> ServiceStatusActive(int id)
        {
            var client = _httpClientFactory.CreateClient();
            await client.GetAsync($"{_apiBaseUrl}/api/WorkProcess/ServiceStatusActive/{id}");
            return RedirectToAction("Index");
        }

        public async Task<IActionResult> ServiceStatusPassive(int id)
        {
            var client = _httpClientFactory.CreateClient();
            await client.GetAsync($"{_apiBaseUrl}/api/WorkProcess/ServiceStatusPassive/{id}");
            return RedirectToAction("Index");
        }
    }
}
