using BankBusinessLogic.MailWorker;
using BankContracts.BindingModels;
using BankContracts.BusinessLogicsContracts;
using BankContracts.SearchModels;
using BankContracts.ViewModels;
using BankDatabaseImplement.Models;
using BankDataModels.Models;
using MailKit;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Metadata;
using OperatorApp.Models;
using System.Diagnostics;

namespace OperatorApp.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IDealLogic _dealLogic;
        private readonly IPaymentLogic _paymentLogic;
        private readonly ITransferLogic _transferLogic;
        private readonly IOperatorLogic _operatorLogic;
        private readonly IReportLogic _reportLogic;
        private readonly ICurrencyLogic _currencyLogic;
        private readonly AbstractMailWorker _mailWorker;

        public static OperatorViewModel? Operator;  

        public HomeController(ILogger<HomeController> logger, IDealLogic dealLogic, IPaymentLogic paymentLogic, ITransferLogic transferLogic, IOperatorLogic operatorLogic, IReportLogic reportLogic, ICurrencyLogic currencyLogic, AbstractMailWorker mailWorker)
        {
            _logger = logger;
            _dealLogic = dealLogic;
            _paymentLogic = paymentLogic;
            _transferLogic = transferLogic;
            _operatorLogic = operatorLogic;
            _reportLogic = reportLogic;
            _currencyLogic = currencyLogic;
            _mailWorker = mailWorker;
        }

        public IActionResult Index()
        {
            if (HomeController.Operator == null)
            {
                return Redirect("~/Home/Enter");
            }
            return View(_dealLogic.ReadList(new DealSearchModel { OperatorId = HomeController.Operator.Id }));
        }

        [HttpGet]
        public IActionResult Privacy()
        {
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                return Redirect("/Home/Enter");
            }
            return View(HomeController.Operator);
        }

        [HttpPost]
        public void Privacy(string login, string password, string lastname, string firstname, string middleName)
        {
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                return;
            }
            if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(lastname) || string.IsNullOrEmpty(firstname) || string.IsNullOrEmpty(middleName))
            {
                throw new Exception("Введите логин, пароль и ФИО");
            }
            _operatorLogic.Update(new OperatorBindingModel
            {
                Id = HomeController.Operator.Id,
                LastName = lastname,
                FirstName = firstname,
                MiddleName = middleName,
                Login = login,
                Password = password
            });

            HomeController.Operator.LastName = lastname;
            HomeController.Operator.FirstName = firstname;
            HomeController.Operator.MiddleName = middleName;
            HomeController.Operator.Login = login;
            HomeController.Operator.Password = password;
            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))
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('Input login and password!');window.location.replace('/Home/Enter');</script>");
                return;
            }
            HomeController.Operator = _operatorLogic.ReadElement(new OperatorSearchModel { Login = login, Password = password });
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('Wrong login or password!');window.location.replace('/Home/Enter');</script>");
                return;
            }
            Response.Redirect("Index");
        }

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

        [HttpPost]
        public void Register(string login, string password, string lastname, string firstname, string middleName)
        {
            if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(lastname) || string.IsNullOrEmpty(firstname) || string.IsNullOrEmpty(middleName))
            {
                throw new Exception("Введите логин, пароль и ФИО");
            }
            _operatorLogic.Create(new OperatorBindingModel
            {
                LastName = lastname,
                FirstName = firstname,
                MiddleName = middleName,
                Login = login,
                Password = password
            });
            Response.Redirect("Enter");
            return;
        }
        [HttpGet]
        public IActionResult CreateDeal()
        {
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                return Redirect("/Home/Enter");
            }
            return View();
        }

        [HttpPost]
        public void CreateDeal(int clientid)
        {
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                return;
            }
            _dealLogic.Create(new DealBindingModel
            {
                ClientId = clientid,
                OperatorId = HomeController.Operator.Id,
            });
            Response.Redirect("Index");
        }
        public IActionResult Payments()
        {
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                return Redirect("/Home/Enter");
            }
            return View(_paymentLogic.ReadList(new PaymentSearchModel { OperatorId = HomeController.Operator.Id }));
        }
        [HttpGet]
        public IActionResult CreatePayment()
        {
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                return Redirect("/Home/Enter");
            }
            ViewBag.Deals = _dealLogic.ReadList(new DealSearchModel { OperatorId = HomeController.Operator.Id });
            return View();
        }
        [HttpPost]
        public void CreatePayment(List<int> deals)
        {
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                return;
            }
            Dictionary<int, IDealModel> DealPayments = new();
            foreach (int id in deals)
            {
                var deal = _dealLogic.ReadElement(new DealSearchModel { Id = id });
                if (deal != null) DealPayments.Add(deal.Id, deal);
            }
            _paymentLogic.Create(new PaymentBindingModel { OperatorId = HomeController.Operator.Id, DealPayments = DealPayments, });
            Response.Redirect("Payments");
        }
        [HttpGet]
        public IActionResult Payment(int id)
        {
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                return Redirect("/Home/Enter");
            }
            return View(_paymentLogic.ReadElement(new PaymentSearchModel { Id = id }));
        }
        [HttpGet]
        public IActionResult Transfers()
        {
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                return Redirect("/Home/Enter");
            }
            return View(_transferLogic.ReadList(new TransferSearchModel { OperatorId = HomeController.Operator.Id }));
        }
        [HttpGet]
        public IActionResult CreateTransfer()
        {
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                return Redirect("/Home/Enter");
            }
            ViewBag.Payments = _paymentLogic.ReadList(new PaymentSearchModel { OperatorId = HomeController.Operator.Id });
            return View();
        }
        [HttpPost]
        public void CreateTransfer(string amount, int payment)
        {
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                return;
            }

            _transferLogic.Create(new TransferBindingModel { OperatorId = HomeController.Operator.Id, Amount = (float)Convert.ToDouble(amount), PaymentId = payment });
            Response.Redirect("Transfers");
        }
        public void DeleteTransfer(int id)
        {
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
            }
            _transferLogic.Delete(new TransferBindingModel { Id = id });
            Response.Redirect("/Home/Transfers");
        }

        [HttpGet]
        public IActionResult PaymentsReport()
        {
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                return Redirect("/Home/Enter");
            }
            ViewBag.Payments = _paymentLogic.ReadList(new PaymentSearchModel { OperatorId = HomeController.Operator.Id });
            return View();
        }

        [HttpPost]
        public IActionResult PaymentsReport(List<int> payments, string doctype, string filename)
        {
            if (string.IsNullOrEmpty(filename)) filename = "report";
            filename = filename.Replace(".", string.Empty);
            List<PaymentBindingModel> paymentBindings = new List<PaymentBindingModel>();
            foreach (int paymentId in payments)
            {
                var paymentView = _paymentLogic.ReadElement(new PaymentSearchModel { Id = paymentId });
                if (paymentView != null) paymentBindings.Add(new PaymentBindingModel
                {
                    Id = paymentView.Id,
                    OperatorId = paymentView.OperatorId,
                    PaymentDate = paymentView.PaymentDate,
                    CurrencyPayments = paymentView.CurrencyPayments,
                    DealPayments = paymentView.DealPayments
                });
            }
            if (doctype.Equals("word"))
            {
                if (!filename.EndsWith(".docx")) filename += ".docx";
                MemoryStream list = _reportLogic.SavePaymentPurchaseToWord(new ReportBindingModel { FileName = filename }, paymentBindings);
                return File(list, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", filename);
            }
            else
            {
                if (!filename.EndsWith(".xlsx")) filename += ".xlsx";
                MemoryStream list = _reportLogic.SavePaymentPurchaseToExcel(new ReportBindingModel { FileName = filename }, paymentBindings);
                return File(list, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename);
            }
        }

        [HttpGet]
        public IActionResult TransfersReport()
        {
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                return Redirect("/Home/Enter");
            }
            return View(new ReportBindingModel());
        }
        [HttpPost]
        public IActionResult TransfersReport(DateTime dateFrom, DateTime dateTo, string reptype, string email, string fileName)
        {
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                return Redirect("/Home/Enter");
            }
            if (reptype.Equals("onForm"))
            {
                ViewBag.DateFrom = dateFrom.ToShortDateString();
                ViewBag.DateTo = dateTo.ToShortDateString();
                return View("ViewReport", _reportLogic.GetTransferPurchase(new ReportBindingModel { DateFrom = dateFrom, DateTo = dateTo }));
            }
            MemoryStream report = _reportLogic.SaveTransferPurchaseToPDF(new ReportBindingModel { DateFrom = dateFrom, DateTo = dateTo });
            try
            {
                if (string.IsNullOrEmpty(fileName)) fileName = "report";
                fileName = fileName.Replace(".", string.Empty);
                if (!fileName.EndsWith(".pdf")) fileName += ".pdf";
                _mailWorker.MailSendAsync(new MailSendInfoBindingModel
                {
                    Subject = "Отчёт о закупках",
                    Text = "Для оператора " + HomeController.Operator.LastName + HomeController.Operator.FirstName,
                    MailAddress = email,
                    FileName = fileName,
                    Attachment = report
                });
                Response.WriteAsync($"<script language=\"javascript\">alert('Mail sent!');window.location.replace('/');</script>");
                return Redirect("/");
            }
            catch (Exception ex)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('{ex.Message}');</script>");
                return Redirect("/");
            }
        }
        [HttpGet]
        public IActionResult AddCurrenciesToPayment()
        {
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                return Redirect("/Home/Enter");
            }
            ViewBag.Currencies = _currencyLogic.ReadList(null);
            ViewBag.Payments = _paymentLogic.ReadList(null);
            return View();
        }
        [HttpPost]
        public void AddCurrenciesToPayment(int payment, List<int> currencies)
        {
            if (HomeController.Operator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                Redirect("/Home/Enter");
            }
            var paymentModel = _paymentLogic.ReadElement(new PaymentSearchModel { Id = payment });
            Dictionary<int, ICurrencyModel> updCurrencies = new Dictionary<int, ICurrencyModel>();
            foreach (var currencyId in currencies)
            {
                var currency = _currencyLogic.ReadElement(new CurrencySearchModel { Id = currencyId });
                if (currency != null) updCurrencies.Add(currencyId, currency);
            }
            _paymentLogic.Update(new PaymentBindingModel { Id = paymentModel.Id, PaymentDate = paymentModel.PaymentDate, CurrencyPayments = updCurrencies });
            Response.WriteAsync($"<script language=\"javascript\">alert('Success!');window.location.replace('/Home/Enter');</script>");
            Redirect("/");
        }
    }
}