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;

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 ICurrencyPurchaseLogic _currencyPurchaseLogic;

        public HomeController(ILogger<HomeController> logger, IBankOperatorLogic bankOperatorLogic,
            ICreditProgramLogic creditProgramLogic, ICurrencyLogic currencyLogic, 
            ICurrencyPurchaseLogic currencyPurchaseLogic)
        {
            _logger = logger;
            _bankOperatorLogic = bankOperatorLogic;
            _creditProgramLogic = creditProgramLogic;
            _currencyLogic = currencyLogic;
            _currencyPurchaseLogic = currencyPurchaseLogic;
        }

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

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

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

            APIClient.BankOperator.LastName = lastname;
            APIClient.BankOperator.FirstName = firstname;
            APIClient.BankOperator.MiddleName = middleName;
            APIClient.BankOperator.Login = login;
            APIClient.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("Введите логин и пароль");
            }
            APIClient.BankOperator = APIClient.
                GetRequest<BankOperatorViewModel>
                ($"api/bankoperator/login?login={login}&password={password}");
            if (APIClient.BankOperator == null)
            {
                throw new Exception("Неверный логин/пароль");
            }
            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("Введите логин, пароль и ФИО");
            }
            APIClient.PostRequest("api/bankoperator/createbankoperator", 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 (APIClient.BankOperator == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }
            APIClient.PostRequest("api/currency/createcurrency", new CurrencyBindingModel
            {
                BankOperatorId = APIClient.BankOperator.Id,
                Name = name,
            });
            Response.Redirect("Index");
        }
        public IActionResult CreditPrograms()
        {
            if (APIClient.BankOperator == null)
            {
                return Redirect("~/Home/Enter");
            }
            return View(APIClient.GetRequest
                <List<PaymentViewModel>>
                ($"api/creditprogram/getcreditprograms?bankoperatorId={APIClient.BankOperator.Id}"));
        }
        [HttpGet]
        public IActionResult CreateCreditProgram()
        {
            ViewBag.Currencies = APIClient.GetRequest<List<CurrencyViewModel>>
                ("api/currency/getcurrencieslist");
            return View();
        }
        [HttpPost]
        public void CreateCreditProgram(List<int> currenciess)
        {
            if (APIClient.BankOperator == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }
            Dictionary<int, ICurrencyModel> CurrencyCreditPrograms = new();
            foreach (int id in currenciess)
            {
                var currency = _currencyLogic.ReadElement(new CurrencySearchModel { Id = id });
                if (currency != null) CurrencyCreditPrograms.Add(currency.Id, currency);
            }
            _creditProgramLogic.Create(new CreditProgramBindingModel { BankOperatorId = 
                APIClient.BankOperator.Id,
                CreditProgramCurrencies = CurrencyCreditPrograms, });
            Response.Redirect("Payments");
        }
        [HttpGet]
        public IActionResult CreditProgram(int id)
        {
            return View(_creditProgramLogic.ReadElement(new CreditProgramSearchModel { Id = id }));
        }
        [HttpGet]
        public IActionResult CurrencyPurchase()
        {
            if (APIClient.BankOperator == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }
            return View(_currencyPurchaseLogic.ReadList
                (new CurrencyPurchaseSearchModel { BankOperatorId = APIClient.BankOperator.Id }));
        }
        [HttpGet]
        public IActionResult CreateCurrencyPurchase()
        {
            if (APIClient.BankOperator == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }
            ViewBag.Currency = _currencyLogic.ReadList
                (new CurrencySearchModel { BankOperatorId = APIClient.BankOperator.Id });
            return View();
        }
        [HttpPost]
        public void CreateCurrencyPurchase(string amount, int currencyId)
        {
            if (APIClient.BankOperator == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }

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

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