using BankYouBankruptClientApp.Models;
using BankYouBankruptContracts.BindingModels;
using BankYouBankruptContracts.ViewModels;
using BankYouBankruptContracts.ViewModels.Client.Default;
using BankYouBankruptContracts.ViewModels.Client.Reports;
using BankYouBankruptContracts.ViewModels.Client.Diagram;
using BankYouBankruptDataModels.Enums;
using BankYouBankruptСlientApp;
using Microsoft.AspNetCore.Mvc;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Xml.Linq;

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

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

        #region Профиль, вход и регистрация

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

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

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

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

		[HttpPost]
        public IActionResult Login(string login, string password)
        {
            if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
            {
				APIClient.SetErrorMessage("Введите логин и пароль");

				return Redirect("ErrorPage");
			}

            APIClient.Client = APIClient.GetRequest<ClientViewModel>($"api/Client/Login?login={login}&password={password}");

            if (APIClient.Client == null)
            {
                APIClient.SetErrorMessage("Неверный логин или пароль");

				return Redirect("ErrorPage");
			}

            return Redirect("Enter");
        }


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


        [HttpPost]
        public void Register(string login, string password, string name, string surname, string patronymic, string telephone)
        {
            if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(name)
                || string.IsNullOrEmpty(surname) || string.IsNullOrEmpty(patronymic) || string.IsNullOrEmpty(telephone))
            {
				APIClient.SetErrorMessage("Проверьте правильность заполнения полей");

				Response.Redirect("ErrorPage");
			}

            APIClient.PostRequest("api/Client/Register", new ClientBindingModel
            {
                Name = name,
                Surname = surname,
                Patronymic = patronymic,
                Email = login,
                Password = password,
                Telephone = telephone
            });

            Response.Redirect("Enter");

            return;
        }

        [HttpPost]
        public IActionResult Logout() 
        {
            APIClient.Client = null;

            return Redirect("~/Home/Enter");
        }

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

            return View(APIClient.Client);
        }

        [HttpPost]
        public void Privacy(string login, string password, string name, string surname, string patronymic, string telephone)
        {
            if (APIClient.Client == null)
            {
                throw new Exception("Вы как сюда попали? Суда вход только авторизованным");
            }

            if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(name)
                || string.IsNullOrEmpty(surname) || string.IsNullOrEmpty(patronymic)
                || string.IsNullOrEmpty(telephone))
            {
				APIClient.SetErrorMessage("Проверьте правильность заполнения полей");

				Response.Redirect("ErrorPage");
			}

            APIClient.PostRequest("/api/Client/UpdateData", new ClientBindingModel
            {
                Id = APIClient.Client.Id,
                Name = name,
                Surname = surname,
                Patronymic = patronymic,
                Telephone = telephone,
                Email = login,
                Password = password
            });

            APIClient.Client.Name = name;
            APIClient.Client.Surname = surname;
            APIClient.Client.Patronymic = patronymic;
            APIClient.Client.Email = login;
            APIClient.Client.Password = password;
            APIClient.Client.Telephone = telephone;

            Response.Redirect("Enter");
        }

        #endregion

        #region Карты
        [HttpGet]
        public IActionResult CardsList()
        {
            if (APIClient.Client == null)
            {
                return Redirect("~/Home/Enter");
            }

            return View(APIClient.GetRequest<List<CardViewModel>>($"api/Card/GetUsersCardsList?id={APIClient.Client.Id}"));
        }

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

            ViewBag.Accounts = APIClient.GetRequest<List<AccountViewModel>>($"api/Account/SearchAccountsOfCLient?clientId={APIClient.Client.Id}");
            return View();
        }

        [HttpPost]
        public IActionResult CreateCard(string accountId, string number, string cvc, DateTime period) {
            if (APIClient.Client == null)
            {
				APIClient.SetErrorMessage("Необходимо авторизоваться");

				return Redirect("ErrorPage");
			}

            if(string.IsNullOrEmpty(accountId) || string.IsNullOrEmpty(number) || string.IsNullOrEmpty(cvc) 
                || period.Year == 0001 || period <= DateTime.Now)
            {
				APIClient.SetErrorMessage("Проверьте корректность параметров создаваемой карты");

				return Redirect("ErrorPage");
			}

            APIClient.PostRequest("api/Card/CreateCard", new CardBindingModel {
                ClientID = APIClient.Client.Id,
                AccountId = int.Parse(accountId),
                Number = number,
                CVC = cvc,
                Period = period
            });

            return Redirect("~/Home/CardsList");
        }

        #endregion

        #region Снятие средств

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

            return View(APIClient.GetRequest<List<DebitingViewModel>>($"api/Client/getUsersDebitings?userId={APIClient.Client.Id}"));
        }

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

            ViewBag.Cards = APIClient.GetRequest<List<CardViewModel>>($"api/Card/GetUsersCardsList?id={APIClient.Client.Id}");
            return View();
        }

        [HttpPost]
        public IActionResult CreateDebiting(string cardId, int sum)
        {
            if (APIClient.Client == null)
            {
				APIClient.SetErrorMessage("Необходимо авторизоваться");

				return Redirect("ErrorPage");
			}

            if(string.IsNullOrEmpty(cardId) || sum <= 0)
            {
				APIClient.SetErrorMessage("Необходимо ввести корректную сумму для снятия");

				return Redirect("ErrorPage");
			}

            APIClient.PostRequest("api/Card/CreateDebitingRequest", new DebitingBindingModel()
            {
                CardId = int.Parse(cardId),
                Sum = sum,
                DateOpen = DateTime.Now,
                Status = StatusEnum.Открыта
            });

            return Redirect("~/Home/DebitingList");
        }

        #endregion

        #region Пополнение средств

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

            return View(APIClient.GetRequest<List<CreditingViewModel>>($"api/Client/getUsersCreditings?userId={APIClient.Client.Id}"));
        }

        [HttpGet]
        public IActionResult CreateCrediting()
        {
            if (APIClient.Client == null)
            {
                return Redirect("~/Home/Enter");
            }
           
			ViewBag.Cards = APIClient.GetRequest<List<CardViewModel>>($"api/Card/GetUsersCardsList?id={APIClient.Client.Id}");
			return View();
        }

        [HttpPost]
        public IActionResult CreateCrediting(string cardId, int sum)
        {
            if (APIClient.Client == null)
            {
                throw new Exception("Не авторизованы");
            }

			if (string.IsNullOrEmpty(cardId) || sum <= 0)
			{
				APIClient.SetErrorMessage("Необходимо ввести корректную сумму для пополнения");

				return Redirect("ErrorPage");
			}

			APIClient.PostRequest("api/Card/CreateCreditingOperation", new CreditingBindingModel()
            {
                CardId = int.Parse(cardId),
                Sum = sum,
                DateOpen = DateTime.Now,
                Status = StatusEnum.Открыта
            });

            return Redirect("~/Home/CreditingList");
        }

        #endregion

        #region Получение отчёта PDF

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

			return View();
        }

        [HttpPost]
        public IActionResult CreateReport(DateTime dateFrom, DateTime dateTo)
        {
            if (APIClient.Client == null)
            {
                throw new Exception("Не авторизованы");
            }

			if (dateFrom == dateTo || dateFrom > dateTo || dateFrom.Year == 0001 || dateTo.Year == 0001)
			{
				APIClient.SetErrorMessage("Необходимо задать корректные границы периода");

				return Redirect("ErrorPage");
			}

			return View(APIClient.PostRequestReport<ReportClientViewModelForHTML, ReportSupportBindingModel>("api/Report/CreateClientReport", new ReportSupportBindingModel()
            {
                DateFrom = dateFrom,
                DateTo = dateTo,
                Email = APIClient.Client.Email
            }));
		}

        #endregion

        #region Excel отчёты

        //отчёт клиента по переводам
        [HttpPost]
        public IActionResult CreateExcelReport(List<CheckboxViewModel> cards)
        {
            if (APIClient.Client == null)
            {
                APIClient.SetErrorMessage("Не авторизованы");

                return Redirect("ErrorPage");
            }

            if (cards.Count == 0 || cards.Count == cards.Where(x => x.IsChecked == false).ToList().Count)
            {
                APIClient.SetErrorMessage("Необходимо выбрать хотя-бы 1 карту для отчёта");

                return Redirect("ErrorPage");
            }

            APIClient.PostRequest("api/Report/CreateExcelClient", new ReportSupportBindingModel()
            {
                CardList = cards.Where(x => x.IsChecked).Select(x => x.Id).ToList(),
                Email = APIClient.Client.Email
            });

            return Redirect("ReportSuccess");
        }

        //отчёт клиента по пополнениям
        [HttpPost]
        public IActionResult CreateCreditingExcelReport(List<CheckboxViewModel> cards)
        {
			if (APIClient.Client == null)
			{
				APIClient.SetErrorMessage("Не авторизованы");

				return Redirect("ErrorPage");
			}

			if (cards.Count == 0 || cards.Count == cards.Where(x => x.IsChecked == false).ToList().Count)
			{
				APIClient.SetErrorMessage("Необходимо выбрать хотя-бы 1 карту для отчёта");

				return Redirect("ErrorPage");
			}

			APIClient.PostRequest("api/Report/CreateExcelCrediting", new ReportSupportBindingModel()
			{
				CardList = cards.Where(x => x.IsChecked).Select(x => x.Id).ToList(),
				Email = APIClient.Client.Email
			});

            return Redirect("ReportSuccess");
        }

        //отчёт клиента по снятиям
		[HttpPost]
		public IActionResult CreateDebitingExcelReport(List<CheckboxViewModel> cards)
		{
			if (APIClient.Client == null)
			{
				APIClient.SetErrorMessage("Не авторизованы");

				return Redirect("ErrorPage");
			}

			if (cards.Count == 0 || cards.Count == cards.Where(x => x.IsChecked == false).ToList().Count)
			{
				APIClient.SetErrorMessage("Необходимо выбрать хотя-бы 1 карту для отчёта");

				return Redirect("ErrorPage");
			}

			APIClient.PostRequest("api/Report/CreateExcelDebiting", new ReportSupportBindingModel()
			{
				CardList = cards.Where(x => x.IsChecked).Select(x => x.Id).ToList(),
				Email = APIClient.Client.Email
			});

            return Redirect("ReportSuccess");
        }

		#endregion

		#region Word отчёты клиента 

		//отчёт клиента по переводам
		[HttpPost]
		public IActionResult CreateWordReport(List<CheckboxViewModel> cards)
		{
			if (APIClient.Client == null)
			{
				APIClient.SetErrorMessage("Не авторизованы");

				return Redirect("ErrorPage");
			}

			if (cards.Count == 0 || cards.Count == cards.Where(x => x.IsChecked == false).ToList().Count)
			{
				APIClient.SetErrorMessage("Необходимо выбрать хотя-бы 1 карту для отчёта");

				return Redirect("ErrorPage");
			}

			APIClient.PostRequest("api/Report/CreateWordClient", new ReportSupportBindingModel()
			{
				CardList = cards.Where(x => x.IsChecked).Select(x => x.Id).ToList(),
				Email = APIClient.Client.Email
			});

            return Redirect("ReportSuccess");
        }

		//отчёт клиента по пополнениям
		[HttpPost]
		public IActionResult CreateCreditingWordReport(List<CheckboxViewModel> cards)
		{
			if (APIClient.Client == null)
			{
				APIClient.SetErrorMessage("Не авторизованы");

				return Redirect("ErrorPage");
			}

			if (cards.Count == 0 || cards.Count == cards.Where(x => x.IsChecked == false).ToList().Count)
			{
				APIClient.SetErrorMessage("Необходимо выбрать хотя-бы 1 карту для отчёта");

				return Redirect("ErrorPage");
			}

			APIClient.PostRequest("api/Report/CreateWordCrediting", new ReportSupportBindingModel()
			{
				CardList = cards.Where(x => x.IsChecked).Select(x => x.Id).ToList(),
				Email = APIClient.Client.Email
			});

            return Redirect("ReportSuccess");
        }

		//отчёт клиента по снятиям
		[HttpPost]
		public IActionResult CreateDebitingWordReport(List<CheckboxViewModel> cards)
		{
			if (APIClient.Client == null)
			{
				APIClient.SetErrorMessage("Не авторизованы");

				return Redirect("ErrorPage");
			}

			if (cards.Count == 0 || cards.Count == cards.Where(x => x.IsChecked == false).ToList().Count)
			{
				APIClient.SetErrorMessage("Необходимо выбрать хотя-бы 1 карту для отчёта");

				return Redirect("ErrorPage");
			}

			APIClient.PostRequest("api/Report/CreateWordDebiting", new ReportSupportBindingModel()
			{
				CardList = cards.Where(x => x.IsChecked).Select(x => x.Id).ToList(),
				Email = APIClient.Client.Email
			});

            return Redirect("ReportSuccess");
        }

		#endregion

		#region Получение отчета по картам
		[HttpGet]
        public IActionResult ReportWithCards()
        {
            if (APIClient.Client == null)
            {
                return Redirect("~/Home/Enter");
            }

            return View(new ReportClientCardsViewModel()
            {
                Cards = APIClient.GetRequest<List<CardViewModel>>($"api/Card/GetUsersCardsList?id={APIClient.Client.Id}").Select(x => new CheckboxViewModel() {
                    Id = x.Id,
                    LabelName = x.Number,
                    IsChecked = false
                }).ToList()
            });
        }

        [HttpPost]
        public IActionResult ReportWithCards(List<CheckboxViewModel> cards)
        {
			if (APIClient.Client == null)
			{
				APIClient.SetErrorMessage("Не авторизованы");

				return Redirect("ErrorPage");
			}

			if (cards.Count == 0 || cards.Count == cards.Where(x => x.IsChecked == false).ToList().Count)
			{
				APIClient.SetErrorMessage("Необходимо выбрать хотя-бы 1 карту для отчёта");

				return Redirect("ErrorPage");
			}

			List<int> cardList = cards.Where(x => x.IsChecked).Select(x => x.Id).ToList();

            List<ReportViewModel> creditings = APIClient.GetRequest<List<CreditingViewModel>>($"api/Client/getUsersCreditings?userId={APIClient.Client.Id}")
                .Where(x => cardList.Contains(x.CardId)).Select(x => new ReportViewModel() {
                    Id = x.Id,
                    CardId = x.CardId,
                    DateOpen = x.DateOpen,
                    DateClose = x.DateClose,
                    CardNumber = x.CardNumber,
                    Status = x.Status,
                    Sum = x.Sum,
                    TypeOperation = TypeOperationEnum.Пополнение
                }).ToList();

            List<ReportViewModel> debitings = APIClient.GetRequest<List<DebitingViewModel>>($"api/Client/getUsersDebitings?userId={APIClient.Client.Id}")
                .Where(x => cardList.Contains(x.CardId)).Select(x => new ReportViewModel()
                {
                    Id = x.Id,
                    CardId = x.CardId,
                    DateOpen = x.DateOpen,
                    DateClose = x.DateClose,
                    CardNumber = x.CardNumber,
                    Status = x.Status,
                    Sum = x.Sum,
                    TypeOperation = TypeOperationEnum.Снятие
                }).ToList();

            List<ReportViewModel> result = creditings.Concat(debitings).OrderBy(x => x.DateOpen).ToList();

            return View(new ReportClientCardsViewModel()
            {
                Cards = cards,
                Operations = result,
            });
        }
		#endregion

		#region Диаграмма

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

            ViewBag.Cards = APIClient.GetRequest<List<CardViewModel>>($"api/Card/GetUsersCardsList?id={APIClient.Client.Id}");
            
            return View();
        }

        [HttpPost]
        public IActionResult Diagram(int cardId)
        {
			if (APIClient.Client == null)
			{
				APIClient.SetErrorMessage("Не авторизованы");

				return Redirect("ErrorPage");
			}

			ViewBag.Cards = APIClient.GetRequest<List<CardViewModel>>($"api/Card/GetUsersCardsList?id={APIClient.Client.Id}");

            return View(new ClientDiagramViewModel() {
                DiagramName = "Hello World",
                Elements = APIClient.GetRequest<List<ClientDiagramElementsViewModel>>($"api/Card/getCardMonthResult?cardId={cardId}") 
            });
        }

        #endregion

        [HttpGet]
        public IActionResult ReportSuccess()
        {
			if (APIClient.Client == null)
			{
				APIClient.SetErrorMessage("Не авторизованы");

				return Redirect("ErrorPage");
			}

			return View();
        }
    }
}