using FurnitureAssemblyWorkerClientApp.Models;
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using FurnitureAssemblyDataModels.Models;
using System;
using FurnitureAssemblyContracts.SearchModels;

namespace FurnitureAssemblyWorkerClientApp.Controllers
{
	public class HomeController : Controller
	{
		private readonly ILogger<HomeController> _logger;
		public HomeController(ILogger<HomeController> logger)
		{
			_logger = logger;
		}
		[HttpGet]
		public IActionResult Index()
		{
			if (APIClient.User == null)
			{
				return Redirect("~/Home/Enter");
			}
			return View(APIClient.GetRequest<List<OrderViewModel>>($"api/order/getorderlistbyuser?userId={APIClient.User.Id}"));
		}
		[HttpGet]
		public IActionResult Privacy()
		{
			if (APIClient.User == null)
			{
				return Redirect("~/Home/Enter");
			}
			return View(APIClient.User);
		}
		[HttpPost]
		public void Privacy(string login, string password, string name, int roleId)
		{
			if (APIClient.User == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(name))
			{
				throw new Exception("Введите логин, пароль и ФИО");
			}
			APIClient.PostRequest("api/user/updateuser", new UserBindingModel
			{
				Id = APIClient.User.Id,
				Name = name,
				Login = login,
				Password = password,
				RoleId = roleId
			});

			APIClient.User.Name = name;
			APIClient.User.Login = login;
			APIClient.User.Password = password;
			APIClient.User.RoleId = roleId;
			Response.Redirect("Index");
		}
		[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
		public IActionResult Error()
		{
			return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
		}
		[HttpGet]
		public IActionResult Enter()
		{
			return View();
		}
		[HttpPost]
		public void Enter(string login, string password)
		{
			if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
			{
				throw new Exception("Введите логин и пароль");
			}
			APIClient.User = APIClient.GetRequest<UserViewModel>($"api/user/login?login={login}&password={password}");
			if (APIClient.User == null)
			{
				throw new Exception("Неверный логин/пароль");
			}
			Response.Redirect("Index");
		}
		[HttpGet]
		public IActionResult Register()
		{
			return View(APIClient.GetRequest<List<RoleViewModel>>($"api/role/getrolelist"));
		}
		[HttpPost]
		public void Register(string login, string password, string name, int roleId)
		{
			if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(name))
			{
				throw new Exception("Введите логин, пароль и ФИО");
			}
			APIClient.PostRequest("api/user/adduser", new UserBindingModel
			{
				Name = name,
				Login = login,
				Password = password,
				RoleId = roleId
			});
			Response.Redirect("Enter");
			return;
		}
        [HttpGet]
        public IActionResult Sets()
        {
            if (APIClient.User == null)
            {
                return Redirect("~/Home/Enter");
            }
            return View(APIClient.GetRequest<List<SetViewModel>>($"api/set/getsetlistbyuser?userId={APIClient.User.Id}"));
        }
		[HttpGet]
		public IActionResult CreateSet()
		{
			return View();
		}
		[HttpPost]
        public void CreateSet(string name, double cost)
        {
            if (APIClient.User == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }
            if (string.IsNullOrEmpty(name))
            {
                throw new Exception("Название гарнитура не указано");
            }
            if (cost <= 0)
            {
                throw new Exception("Стоимость гарнитура не корректна");
            }
            APIClient.PostRequest("api/set/addset", new SetBindingModel
            {
                Name = name,
                Cost = cost,
				UserId = APIClient.User.Id
            });
            Response.Redirect("Sets");
        }
        [HttpGet]
        public Tuple<SetViewModel, string>? GetSetWithFurnitureModules(int setId)
        {
            var result = APIClient.GetRequest<Tuple<SetViewModel, List<FurnitureModuleViewModel>, List<int>>>
                ($"api/set/getsetwithfurnituremodules?setId={setId}");
            if (result == null)
            {
                return default;
            }
            string furnitureModuleTable = "";
            for (int i = 0; i < result.Item2.Count; i++)
            {
                var furnitureModule = result.Item2[i];
                var count = result.Item3[i];
                furnitureModuleTable += "<tr>";
                furnitureModuleTable += $"<td>{furnitureModule.Name}</td>";
                furnitureModuleTable += $"<td>{furnitureModule.Cost}</td>";
                furnitureModuleTable += $"<td>{furnitureModule.DateCreate}</td>";
                furnitureModuleTable += $"<td>{count}</td>";
                furnitureModuleTable += "</tr>";
            }
            return Tuple.Create(result.Item1, furnitureModuleTable);
        }
		[HttpGet]
		public IActionResult UpdateSet()
		{
			if (APIClient.User == null)
			{
				return Redirect("~/Home/Enter");
			}
            return View(APIClient.GetRequest<List<SetViewModel>>($"api/set/getsetlist"));
		}
		[HttpPost]
		public void UpdateSet(int set, string name, double cost, DateTime dateCreate)
		{
			if (APIClient.User == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(name))
			{
				throw new Exception("Название гарнитура не указано");
			}
			if (cost <= 0)
			{
				throw new Exception("Стоимость гарнитура не корректна");
			}
			var listFurnitureModules = APIClient.GetRequest<Dictionary<int, (IFurnitureModuleModel, int)>>($"api/set/getsetfurnituremodules?setId={set}");
			APIClient.PostRequest("api/set/updateset", new SetBindingModel
			{
				Id = set,
				Name = name,
				Cost = cost,
				DateCreate = dateCreate.Date,
				SetFurnitureModules = listFurnitureModules!
			});
			Response.Redirect("Sets");
		}
		[HttpGet]
		public IActionResult DeleteSet()
		{
			if (APIClient.User == null)
			{
				return Redirect("~/Home/Enter");
			}
			return View(APIClient.GetRequest<List<SetViewModel>>($"api/set/getsetlist"));
		}
		[HttpPost]
		public void DeleteSet(int set)
		{
			if (APIClient.User == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			APIClient.PostRequest("api/set/deleteset", new SetBindingModel
			{
				Id = set,
			});
			Response.Redirect("Sets");
		}
		[HttpGet]
		public IActionResult AddFurnitureModuleInSet()
		{
            if (APIClient.User == null)
            {
                return Redirect("~/Home/Enter");
            }
            return View(Tuple.Create(APIClient.GetRequest<List<SetViewModel>>("api/set/getsetlist"), APIClient.GetRequest<List<FurnitureModuleViewModel>>("api/furnituremodule/getfurnituremodulelist")));
		}
		[HttpPost]
		public void AddFurnitureModuleInSet(int set, int furnitureModule, int count)
		{
			if (APIClient.User == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (count <= 0)
			{
				throw new Exception("Количество должно быть больше 0");
			}
			APIClient.PostRequest("api/set/addfurnituremoduleinset", Tuple.Create(
				new SetSearchModel() { Id = set },
				new FurnitureModuleViewModel() { Id = furnitureModule },
				count
			));
			Response.Redirect("Sets");
		}
		[HttpGet]
		public IActionResult ListSetsFurnitureModulesToFile()
		{
            if (APIClient.User == null)
            {
                return Redirect("~/Home/Enter");
            }
            return View(APIClient.GetRequest<List<SetViewModel>>($"api/set/getsetlist"));
        }
        [HttpPost]
        public void ListSetsFurnitureModulesToFile(int[] setIds, string type)
        {
            if (APIClient.User == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }
            if (setIds.Length <= 0)
            {
                throw new Exception("Количество должно быть больше 0");
            }
			if (string.IsNullOrEmpty(type))
			{
                throw new Exception("Неверный тип отчета");
            }

            List<int> res = new List<int>();
            foreach (var item in setIds)
            {
                res.Add(item);
            }
			if (type == "docx")
			{
                APIClient.PostRequest("api/report/createreporttodocx", new ReportWorkerBindingModel
                {
                    SetIds = res
                });
                Response.Redirect("GetDocxFile");
            } 
			else
			{
                APIClient.PostRequest("api/report/createreporttoxlsx", new ReportWorkerBindingModel
                {
                    SetIds = res
                });
                Response.Redirect("GetXlsxFile");
            }
        }
		[HttpGet]
        public IActionResult GetDocxFile()
        {
            return new PhysicalFileResult("C:\\temp\\word_worker.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        }
        public IActionResult GetXlsxFile()
        {
            return new PhysicalFileResult("C:\\temp\\excel_worker.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        }
    }
}