using Contracts.BindingModels;
using Contracts.BusinessLogicsContracts;
using Contracts.ViewModels;
using GuarantorAPP.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

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

		public HomeController(ILogger<HomeController> logger, GuarantorData data)
		{
			_logger = logger;
			_data = data;
		}
		private bool IsLoggedIn { get { return UserGuarantor.user != null; } }
		private int UserId { get { return UserGuarantor.user!.Id; } }
		public IActionResult IndexNonReg()
		{
			if (!IsLoggedIn)
				return View();
			return RedirectToAction("Index");
		}
		public IActionResult Index()
		{
			if (!IsLoggedIn)
				return RedirectToAction("IndexNonReg");
			return View();
		}
		[HttpGet]
		public IActionResult Enter()
		{
			if (!IsLoggedIn)
				return View();
			return RedirectToAction("Index");
		}
		[HttpPost]
		public void Enter(string login, string password)
		{
			var user = _data.Login(login, password);
			if (user != null)
			{
				UserGuarantor.user = user;
				Response.Redirect("Index");
			}
		}
		[HttpGet]
		public IActionResult Register()
		{
			return View();
		}
		public IActionResult Logout()
		{
			UserGuarantor.user = null;
			return RedirectToAction("IndexNonReg");
		}
		[HttpPost]
		public void Register(string name, string login, string email, string password1, string password2)
		{
			if (password1 == password2 && _data.Register(new() { Email = email, Login = login, Name = name, Password = password1 }))
			{
				Response.Redirect("Index");
			}
		}
		[HttpGet]
		public IActionResult IndexMachine()
		{
			if (UserGuarantor.user != null)
			{
				var machines = _data.GetMachines(UserGuarantor.user.Id);
				return View(machines);
			}
			return RedirectToAction("IndexNonReg");
		}
		[HttpPost]
		public IActionResult IndexMachine(int id)
		{
			_data.DeleteMachine(id);
			return RedirectToAction("IndexMachine");
		}
		[HttpGet]
		public IActionResult CreateMachine(int id)
		{
			var workers = _data.GetWorkers(UserGuarantor.user!.Id);
			ViewBag.AllWorkers = workers;
			if (id != 0)
			{
				var value = _data.GetMachine(id);
				if (value != null)
					return View(value);
			}
			return View(new MachineViewModel());
		}
		[HttpPost]
		public IActionResult CreateMachine(int id, string title, int[] workerIds)
		{
			MachineBindingModel model = new MachineBindingModel();
			model.Id = id;
			model.Title = title;
			model.DateCreate = DateTime.Now;
			model.UserId = UserGuarantor.user!.Id;
			var workers = _data.GetWorkers(UserGuarantor.user!.Id);
			for (int i = 0; i < workerIds.Length; i++)
			{
				var worker = workers!.FirstOrDefault(x => x.Id == workerIds[i]);
				model.MachineWorker[workerIds[i]] = worker;
			}
			bool changed = false;
			if (model.MachineWorker.Count > 0)
			{
				if (id != 0)
				{
					changed = _data.UpdateMachine(model);
				}
				else
				{
					changed = _data.CreateMachine(model);
				}
			}
			if (changed)
				return RedirectToAction("IndexMachine");
			else
			{
				ViewBag.AllWorkers = workers;
				return View(model);
			}
		}
		[HttpGet]
		public IActionResult IndexWorker()
		{
			if (UserGuarantor.user != null)
			{
				var list = _data.GetWorkers(UserGuarantor.user.Id);
				if (list != null)
					return View(list);
				return View(new List<WorkerViewModel>());
			}
			return RedirectToAction("IndexNonReg");
		}
		[HttpPost]
		public void IndexWorker(int id)
		{
			if (UserGuarantor.user != null)
			{
				_data.DeleteWorker(id);
			}
			Response.Redirect("IndexWorker");
		}
		[HttpGet]
		public IActionResult CreateWorker(int id)
		{
			if (id != 0)
			{
				var value = _data.GetWorker(id);
				if (value != null)
					return View(value);
			}
			return View(new WorkerViewModel());
		}
		[HttpPost]
		public IActionResult CreateWorker(WorkerBindingModel model)
		{
			if (model.Id == 0)
			{
				model.UserId = UserGuarantor.user!.Id;
				if (_data.CreateWorker(model))
					return RedirectToAction("IndexWorker");
			}
			else
			{
				if (_data.UpdateWorker(model))
					return RedirectToAction("IndexWorker");
			}
			return View();
		}
		[HttpGet]
		public IActionResult IndexWorkshop()
		{
			if (IsLoggedIn)
			{
				var workshops = _data.GetWorkshops(UserGuarantor.user!.Id);
				return View(workshops);
			}
			return RedirectToAction("IndexNonReg");
		}
		[HttpPost]
		public IActionResult IndexWorkshop(int id)
		{
			_data.DeleteWorkshop(id);
			return RedirectToAction("IndexWorkshop");
		}
		[HttpGet]
		public IActionResult CreateWorkshop(int id)
		{
			var workers = _data.GetWorkers(UserGuarantor.user!.Id);
			ViewBag.AllWorkers = workers;
			if (id != 0)
			{
				var value = _data.GetWorkshop(id);
				if (value != null)
					return View(value);
			}
			return View(new WorkshopViewModel());
		}
		[HttpPost]
		public IActionResult CreateWorkshop(int id, string title, int[] workerIds)
		{
			WorkshopBindingModel model = new WorkshopBindingModel();
			model.Id = id;
			model.Title = title;
			model.DateCreate = DateTime.Now;
			model.UserId = UserGuarantor.user!.Id;
			var workers = _data.GetWorkers(UserGuarantor.user!.Id);
			for (int i = 0; i < workerIds.Length; i++)
			{
				var worker = workers!.FirstOrDefault(x => x.Id == workerIds[i])!;
				model.WorkshopWorker[workerIds[i]] = (worker);
			}
			if (model.WorkshopWorker.Count == 0)
				return RedirectToAction("IndexWorkshop");
			if (id != 0)
			{
				_data.UpdateWorkshop(model);
			}
			else
			{
				_data.CreateWorkshop(model);
			}
			return RedirectToAction("IndexWorkshop");
		}
		[HttpGet]
		public IActionResult Privacy()
		{
			if (IsLoggedIn)
				return View(UserGuarantor.user);
			return RedirectToAction("IndexNonReg");
		}
		[HttpPost]
		public IActionResult Privacy(int id, string login, string email, string password, string name)
		{
			if (!IsLoggedIn)
				return RedirectToAction("IndexNonReg");
			GuarantorBindingModel user = new() { Id = id, Login = login, Email = email, Password = password, Name = name };
			if (_data.UpdateUser(user))
			{
				UserGuarantor.user = new GuarantorViewModel { Id = id, Login = login, Password = password, Name = name, Email = email };
			}
			return View(user);
		}
		[HttpGet]
		public IActionResult MachineWorkshopTimeChoose()
		{
			if (!IsLoggedIn)
				return RedirectToAction("IndexNonReg");
			return View();
		}
		[HttpPost]
		public IActionResult SendReport(DateTime startDate, DateTime endDate)
		{
			return Ok();
		}
		[HttpPost]
		public IActionResult TimeReportWeb(DateTime startDate, DateTime endDate)
		{
			if (!IsLoggedIn)
				return RedirectToAction("IndexNonReg");
			HttpContext.Session.SetString("StartDate", startDate.ToString());
			HttpContext.Session.SetString("EndDate", endDate.ToString());
			return RedirectToAction("MachineWorkshopTimeReport");
		}
		[HttpGet]
		public IActionResult MachineWorkshopTimeReport()
		{
			var startDateStr = HttpContext.Session.GetString("StartDate");
			var endDateStr = HttpContext.Session.GetString("EndDate");
			var startDate = DateTime.Parse(startDateStr);
			var endDate = DateTime.Parse(endDateStr).AddDays(1);

			var values = _data.GetTimeReport(startDate, endDate, UserId);
			ViewBag.StartDate = startDate;
			ViewBag.EndDate = endDate;
			return View(values);
		}
		public IActionResult WorkerProductReport()
		{
			List<WorkerProductReportViewModel> workerProductReports = new List<WorkerProductReportViewModel>
			{
				new WorkerProductReportViewModel
				{
					WorkerName = "Работник 1",
					Products = new List<string> { "Изделие первое", "Изделие второе" }
				},
				new WorkerProductReportViewModel
				{
					WorkerName = "Работник 2",
					Products = new List<string> { "Изделие одно", "Изделие второе" }
				}
			};
			return View(workerProductReports);
		}
		public IActionResult ReportsMenu()
		{
			return View();
		}
		[HttpGet]
		public IActionResult WorkshopProductionAdd(int id)
		{
			if (!IsLoggedIn)
				return RedirectToAction("IndexNonReg");
			var workshop = _data.GetWorkshop(id);
			ViewBag.Workshop = workshop;
			var productions = _data.GetProductions();
			return View(productions);
		}
		[HttpPost]
		public IActionResult WorkshopProductionAdd(int workshopId, int productionId)
		{
			if (!IsLoggedIn)
				return RedirectToAction("IndexNonReg");
			var workshop = _data.GetWorkshop(workshopId);
			if (workshop == null)
				return RedirectToAction("Index");
			WorkshopBindingModel workshopBinding = new() { Id = workshopId, Title = workshop.Title, Address = workshop.Address, Director = workshop.Director, UserId = workshop.UserId, ProductionId = workshop.ProductionId, WorkshopWorker = workshop.WorkerWorkshops };
			_data.UpdateWorkshop(workshopBinding);
			return RedirectToAction("IndexWorkshop");
		}
		[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
		public IActionResult Error()
		{
			return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
		}
	}
}