using Microsoft.AspNetCore.Mvc;
using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.ViewModels;
using ShipyardShopApp.Models;
using System.Diagnostics;

namespace ShipyardShopApp.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }
        [HttpGet]
        public IActionResult Enter() 
        {
            return View();
        }

        [HttpPost]
        public void Enter(string password)
        {
            if (string.IsNullOrEmpty(password)) 
            {
                throw new Exception("password");
            }
            if (!APIClient.CheckPassword(password))
            {
                throw new Exception("Не верный пароль");
            }
            Response.Redirect("Index");
        }


        public IActionResult Index()
        {
            if (APIClient.Access == false)
            {
                return Redirect("~/Home/Enter");
            }
            return View(APIClient.GetRequest<List<ShopViewModel>>($"api/shop/getshops"));
        }


        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }


        public IActionResult Create()
        {
            if (APIClient.Access == false)
            {
                return Redirect("~/Home/Enter");
            }
            return View();
        }

        [HttpPost]
        public void Create(string name, string address, DateTime date, int capacity) 
        {
            if (APIClient.Access == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }
            if (capacity <= 0)
            {
                throw new Exception("Вместимость должна быть больше 0");
            }
            if (string.IsNullOrEmpty(name)) 
            {
                throw new Exception("Введите имя");
            }
            if (string.IsNullOrEmpty(address))
            {
                throw new Exception("Введите адрес");
            }
            APIClient.PostRequest("api/shop/createshop", new ShopBindingModel
            {
                ShopName = name,
                Address = address,
                DateOpen = date,
                Capacity = capacity
            });
            Response.Redirect("Index");
        }

        public IActionResult Delete()
        {
            if (APIClient.Access == false)
            {
                return Redirect("~/Home/Enter");
            }
            ViewBag.Shops = APIClient.GetRequest<List<ShopViewModel>>("api/shop/getshops");
            return View();
        }

        [HttpPost]
        public void Delete(int shopId) 
        {
            if (APIClient.Access == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }
            APIClient.PostRequest("api/shop/deleteshop", new ShopBindingModel
            {
                Id = shopId
            });
            Response.Redirect("Index");
        }

        public IActionResult AddShip()
        {
            if (APIClient.Access == false)
            {
                return Redirect("~/Home/Enter");
            }
            ViewBag.Shops = APIClient.GetRequest<List<ShopViewModel>>("api/shop/getshops");
            ViewBag.ShopShips = APIClient.GetRequest<List<ShipViewModel>>("api/main/getshiplist");
            return View();
        }


        [HttpPost]
        public void AddShip(int shopId,int shipId,int count)
        {
            if (APIClient.Access == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }
            APIClient.PostRequest("api/shop/addshipinshop", Tuple.Create(
                new ShopSearchModel() { Id=shopId},
                new ShipViewModel() { Id=shipId},
                count
            ));
            Response.Redirect("Index");
        }

        public IActionResult Update()
        {
            if (APIClient.Access == false)
            {
                return Redirect("~/Home/Enter");
            }
            ViewBag.Shops = APIClient.GetRequest<List<ShopViewModel>>("api/shop/getshops");
            return View();
        }

        [HttpPost]
        public void Update(int shopId, string name, string address, DateTime date, int capacity)
        {
            if (APIClient.Access == false)
            {
                throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
            }
            if (string.IsNullOrEmpty(name))
            {
                throw new Exception("Название магазина не может быть пустым");
            }
            if (string.IsNullOrEmpty(address))
            {
                throw new Exception("Адрес магазина не может быть пустым");
            }
            if (capacity <= 0)
            {
                throw new Exception("Вместимость магазина не может быть меньше нуля");
            }
            APIClient.PostRequest("api/shop/updateshop", new ShopBindingModel
            {
                Id = shopId,
                ShopName = name,
                Address = address,
                DateOpen = date,
                Capacity = capacity
            });
            Response.Redirect("Index");
        }

        [HttpGet]
        public Tuple<ShopViewModel, string>? GetShop(int shopId)
        {
            if (APIClient.Access == false)
            {
                throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
            }
            var result = APIClient.GetRequest<Tuple<ShopViewModel, List<Tuple<string, int>>>>($"api/shop/getshop?shopid={shopId}");
            if (result == null)
            {
                return default;
            }
            string table = "";
            for (int i = 0; i < result.Item2.Count; i++)
            {
                var sushi = result.Item2[i].Item1;
                var count = result.Item2[i].Item2;
                table += "<tr>";
                table += $"<td>{sushi}</td>";
                table += $"<td>{count}</td>";
                table += "</tr>";
            }
            return Tuple.Create(result.Item1, table);
        }
    }
}