using BankContracts.BindingModels;
using BankContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
using BankOperatorApp.Models;
using System.Diagnostics;
using BankContracts.BusinessLogicsContracts;
using BankContracts.SearchModels;
using BankDataModels.Models;
using BankBusinessLogic.BusinessLogics;
using BankBusinessLogic.MailWorker;

namespace BankOperatorApp.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IBankOperatorLogic _bankOperatorLogic;
        private readonly ICreditProgramLogic _creditProgramLogic;
        private readonly ICurrencyLogic _currencyLogic;
        private readonly ICurrencyPurchaseLogic _currencyPurchaseLogic;
        private readonly IDealLogic _dealLogic;
        private readonly IReportLogic _reportLogic;
        private readonly AbstractMailWorker _mailWorker;
        public static BankOperatorViewModel? BankOperator { get; set; } = null;
        

        public HomeController(ILogger<HomeController> logger, IBankOperatorLogic bankOperatorLogic,
            ICreditProgramLogic creditProgramLogic, ICurrencyLogic currencyLogic, 
            ICurrencyPurchaseLogic currencyPurchaseLogic, IReportLogic reportLogic,
            IDealLogic dealLogic, AbstractMailWorker mailWorker)
        {
            _logger = logger;
            _bankOperatorLogic = bankOperatorLogic;
            _creditProgramLogic = creditProgramLogic;
            _currencyLogic = currencyLogic;
            _currencyPurchaseLogic = currencyPurchaseLogic;
            _reportLogic = reportLogic;
            _dealLogic = dealLogic;
            _mailWorker = mailWorker;
        }

        public IActionResult Index()
        {
            if (HomeController.BankOperator == null)
            {
                return Redirect("~/Home/Enter");
            }
            return View(_currencyLogic.ReadList(new CurrencySearchModel { BankOperatorId = 
                HomeController.BankOperator.Id }));
        }

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

        [HttpPost]
        public void Privacy(string login, string password, string lastname, 
            string firstname, string middleName)
        {
            if (HomeController.BankOperator == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }
            if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(lastname) || string.IsNullOrEmpty(firstname))
            {
                throw new Exception("Введите логин, пароль и ФИО");
            }
            _bankOperatorLogic.Update(new BankOperatorBindingModel
            {
                Id = HomeController.BankOperator.Id,
                LastName = lastname,
                FirstName = firstname,
                MiddleName = middleName,
                Login = login,
                Password = password
            });

            HomeController.BankOperator.LastName = lastname;
            HomeController.BankOperator.FirstName = firstname;
            HomeController.BankOperator.MiddleName = middleName;
            HomeController.BankOperator.Login = login;
            HomeController.BankOperator.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))
            {
                throw new Exception("Введите логин и пароль");
            }
            HomeController.BankOperator = _bankOperatorLogic.ReadElement
                (new BankOperatorSearchModel { Login = login, Password = password });
            if (HomeController.BankOperator == 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("Введите логин, пароль и ФИО");
            }
            _bankOperatorLogic.Create(new BankOperatorBindingModel
            {
                LastName = lastname,
                FirstName = firstname,
                MiddleName = middleName,
                Login = login,
                Password = password
            });
            Response.Redirect("Enter");
            return;
        }
        [HttpGet]
        public IActionResult CreateCurrency()
        {
            return View();
        }

        [HttpPost]
        public void CreateCurrency(string name)
        {
            if (HomeController.BankOperator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">" +
                    $"alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                Redirect("/Home/Enter");
            }
            _currencyLogic.Create(new CurrencyBindingModel
            {
                Name = name,
                BankOperatorId = HomeController.BankOperator.Id,
            });
            Response.Redirect("Index");
        }
        public IActionResult CreditPrograms()
        {
            if (HomeController.BankOperator == null)
            {
                return Redirect("~/Home/Enter");
            }
            return View(_creditProgramLogic.ReadList(new CreditProgramSearchModel 
            { BankOperatorId = HomeController.BankOperator.Id}));
        }
        [HttpGet]
        public IActionResult CreateCreditProgram()
        {
            ViewBag.Currencies = _currencyLogic.ReadList(null);
            return View();
        }
        [HttpPost]
        public void CreateCreditProgram(List<int> currencies, string name, float percent)
        {
            if (HomeController.BankOperator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">" +
                    $"alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                Redirect("/Home/Enter");
            }
            Dictionary<int, ICurrencyModel> CurrencyCreditPrograms = new();
            foreach (int id in currencies)
            {
                var currency = _currencyLogic.ReadElement(new CurrencySearchModel { Id = id });
                if (currency != null) CurrencyCreditPrograms.Add(currency.Id, currency);
            }
            _creditProgramLogic.Create(new CreditProgramBindingModel { BankOperatorId = 
                HomeController.BankOperator.Id,
                CreditProgramCurrencies = CurrencyCreditPrograms, Name = name, Percent = percent});
            Response.Redirect("CreditPrograms");
        }
        [HttpGet]
        public IActionResult CreditProgram(int id)
        {
            return View(_creditProgramLogic.ReadElement(new CreditProgramSearchModel { Id = id }));
        }
        [HttpGet]
        public IActionResult CurrencyPurchase()
        {
            if (HomeController.BankOperator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">" +
                    $"alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                return Redirect("/Home/Enter");
            }
            return View(_currencyPurchaseLogic.ReadList
                (new CurrencyPurchaseSearchModel { BankOperatorId = HomeController.BankOperator.Id }));
        }
        [HttpGet]
        public IActionResult CreateCurrencyPurchase()
        {
            if (HomeController.BankOperator == 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);
            return View();
        }
        [HttpPost]
        public void CreateCurrencyPurchase(string amount, int currencyId)
        {
            if (HomeController.BankOperator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">" +
                    $"alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                Redirect("/Home/Enter");
            }

            _currencyPurchaseLogic.Create(new CurrencyPurchaseBindingModel 
            {   BankOperatorId = HomeController.BankOperator.Id, 
                Amount = (float)Convert.ToDouble(amount), 
                CurrencyId = currencyId,

            });
            Response.Redirect("CurrencyPurchases");
        }

        public IActionResult CurrencyPurchases()
        {
            if (HomeController.BankOperator == null)
            {
                return Redirect("~/Home/Enter");
            }
            return View(_currencyPurchaseLogic.ReadList(new CurrencyPurchaseSearchModel
            { BankOperatorId = HomeController.BankOperator.Id }));
        }

        [HttpGet]
        public IActionResult CurrencyReport()
        {
            if (HomeController.BankOperator == 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);
            return View();
        }

        [HttpPost]
        public IActionResult CurrencyReport(List<int> currencies, string doctype)
        {
            List<CurrencyBindingModel> currencyBindings = new List<CurrencyBindingModel>();
            foreach (int currencyId in currencies)
            {
                var currencyView = _currencyLogic.ReadElement
                    (new CurrencySearchModel { Id = currencyId });
                if (currencyView != null) currencyBindings.Add(new CurrencyBindingModel
                {
                    Id = currencyView.Id,
                    BankOperatorId = currencyView.BankOperatorId,
                    Name = currencyView.Name,
                });
            }
            if (doctype.Equals("word"))
            {
                MemoryStream list = _reportLogic.SaveCurrencyTransfersToWord
                    (new ReportBindingModel { FileName = "test" }, currencyBindings);
                return File(list, "application/vnd.openxmlformats-officedocument." +
                    "wordprocessingml.document", "testDoc.docx");
            }
            else
            {
                MemoryStream list = _reportLogic.SaveCurrencyTransfersToExcel
                    (new ReportBindingModel { FileName = "test" }, currencyBindings);
                return File(list, "application/vnd.openxmlformats-officedocument." +
                    "spreadsheetml.sheet", "testExcel.xlsx");
            }
        }


        [HttpGet]
        public IActionResult CurrencyPurchasePaymentsReport()
        {
            if (HomeController.BankOperator == 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 CurrencyPurchasePaymentsReport(DateTime dateFrom,
            DateTime dateTo, string reptype, string email, string fileName)
        {
            if (HomeController.BankOperator == 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.GetPurchasePayment(new ReportBindingModel { DateFrom = dateFrom, DateTo = dateTo }));
            }
            MemoryStream report = _reportLogic.SavePurchasePaymentToPDF(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.BankOperator.LastName + HomeController.BankOperator.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("/");
            }
        }

        public IActionResult AddDealsToCreditProgram()
        {
            if (HomeController.BankOperator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">" +
                    $"alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                return Redirect("/Home/Enter");
            }
            ViewBag.CreditPrograms = _creditProgramLogic.ReadList(new CreditProgramSearchModel { BankOperatorId = HomeController.BankOperator.Id});
            ViewBag.Deals = _dealLogic.ReadList(null);
            return View();
        }

        [HttpPost]
        public void AddDealsToCreditProgram(int creditProgram, List<int> deals)
        {
            if (HomeController.BankOperator == null)
            {
                Response.WriteAsync($"<script language=\"javascript\">alert('You need to login!');window.location.replace('/Home/Enter');</script>");
                Redirect("/Home/Enter");
            }
            foreach (var dealId in deals)
            {
                var deal = _dealLogic.ReadElement(new DealSearchModel { Id = dealId });
                if (deal != null) _dealLogic.Update(new DealBindingModel { Id = deal.Id, ClientId = deal.ClientId, CreditProgramId = creditProgram });
            }
            Response.WriteAsync($"<script language=\"javascript\">alert('Success!');window.location.replace('/');</script>");
            Redirect("/");
        }
    }
}