using ImplementerApp.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using BusinessLogic.BusinessLogic;
using Contracts.BusinessLogicsContracts;
using Contracts.ViewModels;
using DataModels.Models;
using Contracts.BindingModels;
using DatabaseImplement.Models;

namespace ImplementerApp.Controllers
{
	public class HomeController : Controller
	{
		private readonly ILogger<HomeController> _logger;
		private readonly ImplementerData _data;
		public HomeController(ILogger<HomeController> logger, ImplementerData data)
		{
			_logger = logger;
			_data = data;
		}
		private bool IsLoggedIn { get {return UserImplementer.user != null; } }
		private int UserId { get { return UserImplementer.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)
			{
				UserImplementer.user = user;
				Response.Redirect("Index");
			}
		}
		[HttpGet]
		public IActionResult Register()
		{
			return View();
		}
		public IActionResult Logout()
		{
			UserImplementer.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 IndexDetail()
		{
			if (UserImplementer.user != null)
			{
				var list = _data.GetDetails(UserImplementer.user.Id);
				if (list != null)
					return View(list);
				return View(new List<DetailViewModel>());
			}
			return RedirectToAction("IndexNonReg");
		}
		[HttpPost]
		public void IndexDetail(int id)
		{
			if (UserImplementer.user != null)
			{
				_data.DeleteDetail(id);
			}
			Response.Redirect("IndexDetail");
		}
		[HttpGet]
        public IActionResult CreateDetail(int id)
		{
			if (id != 0)
			{
				var value = _data.GetDetail(id);
				if (value != null)
					return View(value);
			}
			return View(new DetailViewModel());
        }
		[HttpPost]
		public IActionResult CreateDetail(DetailBindingModel model)
		{
			if (model.Id == 0)
			{
				model.DateCreate = DateTime.Now;
				model.UserId = UserImplementer.user!.Id;
				if (_data.CreateDetail(model))
					return RedirectToAction("IndexDetail");
			}
			else
			{
				if (_data.UpdateDetail(model))
					return RedirectToAction("IndexDetail");
			}
			return View();
		}
		[HttpGet]
        public IActionResult IndexProduct()
        {
			if (IsLoggedIn) {
				var products = _data.GetProducts(UserImplementer.user!.Id);
				return View(products);
			}
			return RedirectToAction("IndexNonReg");
		}
		[HttpPost]
		public IActionResult IndexProduct(int id)
		{
			_data.DeleteProduct(id);
			return RedirectToAction("IndexProduct");
		}
		[HttpGet]
        public IActionResult CreateProduct(int id)
        {
			var details = _data.GetDetails(UserImplementer.user!.Id);
			ViewBag.AllDetails = details;
            if (id != 0)
			{
				var value = _data.GetProduct(id);
				if (value != null)
					return View(value);
			}
            return View(new ProductViewModel());
        }
		[HttpPost]
		public IActionResult CreateProduct(int id, string title, int[] detailIds, int[] counts)
		{
			ProductBindingModel model = new ProductBindingModel();
			model.Id = id;
			model.Name = title;
			model.UserId = UserImplementer.user!.Id;
			var details = _data.GetDetails(UserImplementer.user!.Id);
			double sum = 0;
			for (int i = 0; i < detailIds.Length; i++)
			{
				var detail = details!.FirstOrDefault(x => x.Id == detailIds[i])!;
				if (counts[i] <= 0)
					continue;
                model.ProductDetails[detailIds[i]] = (detail, counts[i]);
				sum += detail.Cost * counts[i];
			}
			if (model.ProductDetails.Count == 0)
                return RedirectToAction("IndexProduct");
            model.Cost = sum;
			if (id != 0)
			{
				_data.UpdateProduct(model);
			}
			else
			{
				_data.CreateProduct(model);
			}
			return RedirectToAction("IndexProduct");
        }
		[HttpGet]
        public IActionResult IndexProduction()
        {
			if (UserImplementer.user != null)
			{
				var productions = _data.GetProductions(UserImplementer.user.Id);
				return View(productions);
			}
			return RedirectToAction("IndexNonReg");
		}
		[HttpPost]
		public IActionResult IndexProduction(int id)
		{
			_data.DeleteProduction(id);
			return RedirectToAction("IndexProduction");
		}
		[HttpGet]
        public IActionResult CreateProduction(int id)
        {
            var details = _data.GetDetails(UserImplementer.user!.Id);
			ViewBag.AllDetails = details;
			if (id != 0)
			{
				var value = _data.GetProduction(id);
				if (value != null)
					return View(value);
			}
            return View(new ProductionViewModel());
        }
		[HttpPost]
		public IActionResult CreateProduction(int id, string title, int[] detailIds)
		{
            ProductionBindingModel model = new ProductionBindingModel();
            model.Id = id;
            model.Name = title;
            model.UserId = UserImplementer.user!.Id;
            var details = _data.GetDetails(UserImplementer.user!.Id);
            double sum = 0;
            for (int i = 0; i < detailIds.Length; i++)
            {
                var detail = details!.FirstOrDefault(x => x.Id == detailIds[i])!;
                model.ProductionDetails[detailIds[i]] = detail;
                sum += detail.Cost;
            }
            model.Cost = sum;
			bool changed = false;
			if (model.ProductionDetails.Count > 0)
			{
				if (id != 0)
				{
					changed = _data.UpdateProduction(model);
				}
				else
				{
					changed = _data.CreateProduction(model);
				}
			}
			if (changed)
				return RedirectToAction("IndexProduction");
			else
			{
                ViewBag.AllDetails = details;
				return View(model);
            }
        }
		[HttpGet]
        public IActionResult Privacy()
        {
			if (IsLoggedIn)
				return View(UserImplementer.user);
			return RedirectToAction("IndexNonReg");
		}
		[HttpPost]
		public IActionResult Privacy(int id, string login, string email, string password, string name)
		{
			if (!IsLoggedIn)
				return RedirectToAction("IndexNonReg");
			ImplementerBindingModel user = new() { Id = id, Login = login, Email = email, Password = password, Name = name };
			if (_data.UpdateUser(user))
			{
				UserImplementer.user = new ImplementerViewModel { Id = id, Login = login, Password = password, Name = name, Email = email };
			}
			return View(user);
		}
		[HttpGet]
		public IActionResult DetailTimeChoose()
		{
			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("DetailTimeReport");
        }
        [HttpGet]
        public IActionResult DetailTimeReport()
        {
            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 DetailWorkshopReport()
		{
			List<DetailWorkshopReportViewModel> detailWorkshopReports = new List<DetailWorkshopReportViewModel>
			{
				new DetailWorkshopReportViewModel
				{
					DetailName = "Деталь X",
					WorkShops = new List<string> { "Цех 1", "Цех 2" }
				},
				new DetailWorkshopReportViewModel
				{
					DetailName = "Деталь Y",
					WorkShops = new List<string> { "Цех 3", "Цех 4" }
				}
			};
			return View(detailWorkshopReports);
		}
		public IActionResult ReportsMenu()
		{
			return View();
		}
		[HttpGet]
		public IActionResult ProductMachineAdd(int id)
		{
			if (!IsLoggedIn)
				return RedirectToAction("IndexNonReg");
			var product = _data.GetProduct(id);
			ViewBag.Product = product;
			var machines = _data.GetMachines();
            return View(machines);
		}
		[HttpPost]
		public IActionResult ProductMachineAdd(int productId, int machineId) 
		{	
            if (!IsLoggedIn)
                return RedirectToAction("IndexNonReg");
			var product = _data.GetProduct(productId);
			if (product == null)
				return RedirectToAction("Index");
			ProductBindingModel productBinding = new() { Id = productId, Cost = product.Cost, Name = product.Name, UserId = product.UserId, ProductDetails = product.DetailProducts, MachineId = machineId };
			_data.UpdateProduct(productBinding);
			return RedirectToAction("IndexProduct");
			
        }

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