using IceCreamShopApp.Models;
using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.SearchModels;
using IceCreamShopContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace IceCreamShopApp.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("Введите пароль");
			}
			APIClient.GetAccess(password);

            if (APIClient.Access == false)
			{
				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 count)
		{
			if (APIClient.Access == false)
			{
				throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(address)
				|| count <= 0)
			{
				throw new Exception("Введите название");
			}
			if (string.IsNullOrEmpty(address))
			{
				throw new Exception("Введите адресс");
			}
			if (count <= 0)
			{
				throw new Exception("Введите количество");
			}
			APIClient.PostRequest("api/shop/createshop", new ShopBindingModel
			{
				Name = name,
				Adress = address,
				IceCreamMaxCount= count,
				OpeningDate = date
			});
			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 shop)
		{
			if (APIClient.Access == false)
			{
				throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
			}
			APIClient.PostRequest("api/shop/deleteshop", new ShopBindingModel
			{
				Id = shop
			});
			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 shop, string name, string adress, DateTime date, int count)
		{
			if (APIClient.Access == false)
			{
				throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(name))
			{
				throw new Exception("Название магазина не может быть пустым");
			}
			if (string.IsNullOrEmpty(adress))
			{
				throw new Exception("Адрес магазина не может быть пустым");
			}
			if (count <= 0)
			{
				throw new Exception("Вместимость магазина не может быть меньше нуля");
			}
			APIClient.PostRequest("api/shop/updatedata", new ShopBindingModel
			{
				Id = shop,
				Name = name,
				Adress = adress,
				OpeningDate = date,
				IceCreamMaxCount = count
			});
			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 icecream = result.Item2[i].Item1;
				var count = result.Item2[i].Item2;
				table += "<tr>";
				table += $"<td>{icecream}</td>";
				table += $"<td>{count}</td>";
				table += "</tr>";
			}
			return Tuple.Create(result.Item1, table);
		}

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

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