using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.ViewModels;
using ComputerStoreWebApp;
using System.IO.Pipelines;
using ComputerStoreWebApp.Models;

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

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            if (APIUser.User == null)
            {
                return Redirect("~/Home/Enter");
            }
            return View();
        }

        [HttpGet]
        public IActionResult Privacy()
        {
            if (APIUser.User == null)
            {
                return Redirect("~/Home/Enter");
            }
            return View(APIUser.User);
        }

        [HttpPost]
        public void Privacy(string fio, string login, string password, string email)
        {
            if (APIUser.User == null)
            {
                throw new Exception("Требуется авторизация");
            }
            if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(email))
            {
                throw new Exception("Требуется логин, пароль и email");
            }
            APIUser.PostRequest("api/user/updatedata", new UserBindingModel
            {
                Id = APIUser.User.Id,
                FIO = fio,
                Login = login,
                Password = password,
                Email = email
            });

            APIUser.User.FIO = fio;
            APIUser.User.Password = password;
            APIUser.User.Email = email;
            Response.Redirect("Index");
        }

        [HttpGet]
        public IActionResult CreateComponent()
        {
            return View();
        }

        [HttpPost]
        public void CreateComponent(string title, double price, string manufacturer)
        {
            if (string.IsNullOrEmpty(title) || price <= 0 || string.IsNullOrEmpty(manufacturer))
            {
                throw new Exception("Введите название, цену и описание");
            }
            APIUser.PostRequest("api/component/create", new ComponentBindingModel
            {
                ComponentName = title,
                Price = price,
                Manufacturer = manufacturer,
                UserId = APIUser.User.Id
            });
            Response.Redirect("IndexComponent");
        }

        [HttpGet]
        public IActionResult CreateProduct()
        {
            return View();
        }

        [HttpPost]
        public void CreateProduct(string title, string category, double price)
        {
            if (string.IsNullOrEmpty(title) || price <= 0 || string.IsNullOrEmpty(category))
            {
                throw new Exception("Введите название, цену и описание");
            }
            APIUser.PostRequest("api/product/create", new ProductBindingModel
            {
                ProductName = title,
                Category = category,
                Price = price,

                UserId = APIUser.User.Id
            });
            Response.Redirect("IndexProduct");
        }

        [HttpGet]
        public IActionResult CreateRequest()
        {
            var assemblies = APIUser.GetRequest<List<AssemblyViewModel>>("api/assembly/getlist");
            return View(assemblies ?? new List<AssemblyViewModel>());
        }

        [HttpPost]
        public void CreateRequest(int[] assemblies)
        {
            if (assemblies == null || assemblies.Length == 0)
            {
                throw new Exception("Выберите хотя бы одну сборку");
            }
            foreach (var assemblyId in assemblies)
            {
                APIUser.PostRequest("api/request/create", new RequestBindingModel
                {
                    AssemblyId = assemblyId,
                    UserId = APIUser.User.Id
                });
            }
            Response.Redirect("IndexRequest");
        }

        [HttpGet]
        public IActionResult CreateAssembly()
        {
            var components = APIUser.GetRequest<List<ComponentViewModel>>("api/component/getlist");
            return View(components ?? new List<ComponentViewModel>());
        }

        [HttpPost]
        public void CreateAssembly(string assemblyName, string description, int[] components)
        {
            if (string.IsNullOrEmpty(assemblyName) || components == null || components.Length == 0)
            {
                throw new Exception("Введите название сборки и выберите хотя бы одно комплектующее");
            }
            APIUser.PostRequest("api/assembly/create", new AssemblyBindingModel
            {
                AssemblyName = assemblyName,
                Description = description,
                UserId = APIUser.User.Id,
                Components = components.ToList()
            });
            Response.Redirect("IndexAssembly");
        }
        [HttpGet]
        public IActionResult CreateBatch()
        {
            var products = APIUser.GetRequest<List<ProductViewModel>>("api/product/getlist");
            return View(products ?? new List<ProductViewModel>());
        }


        [HttpGet]
        public IActionResult IndexComponent()
        {
            var components = APIUser.GetRequest<List<ComponentViewModel>>("api/component/getlist");
            return View(components ?? new List<ComponentViewModel>());
        }

        [HttpGet]
        public IActionResult IndexProduct()
        {
            var products = APIUser.GetRequest<List<ProductViewModel>>("api/product/getlist");
            return View(products ?? new List<ProductViewModel>());
        }

        [HttpGet]
        public IActionResult IndexRequest()
        {
            var requests = APIUser.GetRequest<List<RequestViewModel>>("api/request/getlist");
            return View(requests ?? new List<RequestViewModel>());
        }

        [HttpGet]
        public IActionResult IndexAssembly()
        {
            var assemblies = APIUser.GetRequest<List<AssemblyViewModel>>("api/assembly/getlist");
            return View(assemblies ?? new List<AssemblyViewModel>());
        }


        [HttpGet]
        public IActionResult ComponentRequestAssemblyReport()
        {
            var reports = APIUser.GetRequest<List<ComponentRequestAssemblyReportViewModel>>("api/report/componentrequestassembly");
            return View(reports ?? new List<ComponentRequestAssemblyReportViewModel>());
        }

        [HttpGet]
        public IActionResult ReportsMenu()
        {
            return View();
        }

        [HttpGet]
        public IActionResult Enter()
        {
            return View();
        }

        [HttpPost]
        public void Enter(string login, string password)
        {
            if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
            {
                throw new Exception("Введите логин и пароль");
            }
            APIUser.User = APIUser.GetRequest<UserViewModel>($"api/user/loginimplementer?login={login}&password={password}");
            if (APIUser.User == null)
            {
                throw new Exception("Неверный логин или пароль");
            }
            Response.Redirect("Index");
        }

        [HttpGet]
        public IActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public void Register(string fio, string login, string password, string email)
        {
            if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(email))
            {
                throw new Exception("Введите логин, пароль, почту");
            }
            APIUser.PostRequest("api/user/registerimplementer", new UserBindingModel
            {
                FIO = fio,
                Login = login,
                Password = password,
                Email = email
            });
            Response.Redirect("Enter");
        }

        [HttpGet]
        public IActionResult DeleteProduct(int id)
        {
            APIUser.PostRequest("api/product/delete", new { Id = id });
            return RedirectToAction("IndexProduct");
        }

        [HttpGet]
        public IActionResult DeleteComponent(int id)
        {
            APIUser.PostRequest("api/component/delete", new { Id = id });
            return RedirectToAction("IndexComponent");
        }

        [HttpGet]
        public IActionResult DeleteAssembly(int id)
        {
            APIUser.PostRequest("api/assembly/delete", new { Id = id });
            return RedirectToAction("IndexAssembly");
        }

        [HttpGet]
        public IActionResult DeleteRequest(int id)
        {
            APIUser.PostRequest("api/request/delete", new { Id = id });
            return RedirectToAction("IndexRequest");
        }

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