using Blazored.Modal;
using Blazored.Modal.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using Seenginx.Models;
using Seenginx.Services;
using Seenginx.Shared;
using Seenginx.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Seenginx.Pages
{
	public class NginxBase : ComponentBase
	{
		[Inject] public INginxService NginxService { get; set; }
		[CascadingParameter] public IModalService Modal { get; set; }

		public string InputSearch { get; set; }

		public List<ConfigFile> ConfigFiles { get; set; } = new List<ConfigFile>();
		public ConfigFile SelectedFile { get; set; }
		public List<int> FilteredOutFiles { get; set; } = new List<int>();
		public NotificationSettings GeneralNotificationSettings { get; set; } = null;
		public List<Template> Templates { get; set; } = new List<Template>();

		protected override async Task OnParametersSetAsync()
		{
			try
			{
				ConfigFiles.AddRange(await NginxService.GetFilesAsync());
				Templates.AddRange(await NginxService.GetTemplates());
			}
			catch (Exception ex)
			{
				throw ex;
			}
			await base.OnParametersSetAsync();
		}

		public void SelectedFileChanged(ConfigFile configFile)
		{
			SelectedFile = configFile;
		}

		public async Task AddFileModal()
		{
			var parameters = new ModalParameters();
			parameters.Add(nameof(Templates), Templates);

			var resultAwait = Modal.Show<NginxConfigForm>(string.Empty, parameters);
			var result = await resultAwait.Result;
			if (result.Cancelled) return;


			var validationResult = await NginxService.ValidateForAddFileAsync((NewFileForm)result.Data);

			if (!validationResult.AllOk)
			{
				var validationPopupParameters = new ModalParameters().Setup(PopupType.Ok, validationResult.ErrorMessage);
				var validationPopup = Modal.Show<GenericPopup>(string.Empty, validationPopupParameters);
				await validationPopup.Result;
				validationPopup.Close();
				return;
			}

			var addFileResult = await NginxService.AddFileAsync((NewFileForm)result.Data);
			if (SelectedFile != null)
				SelectedFile.Deselect();
			ConfigFiles.Add(addFileResult.Data);
			ConfigFiles = ConfigFiles.OrderBy(cf => cf.Name).ToList();
			SelectedFile = ConfigFiles.Find(cf => cf.Name == addFileResult.Data.Name);
			SelectedFile.Select();
		}

		public async Task RenameFileModal()
		{
			var parameters = new ModalParameters();
			parameters.Add(nameof(RenameForm.Name), SelectedFile.Name);

			var resultAwait = Modal.Show<RenameForm>(string.Empty, parameters);
			var result = await resultAwait.Result;
			if (result.Cancelled) return;

			var validationResult = await NginxService.ValidateForRenameFileAsync(ConfigFiles, SelectedFile, result.Data.ToString());
			if (!validationResult.AllOk)
			{
				var popupAwait = Modal.Show<GenericPopup>(string.Empty, new ModalParameters().Setup(PopupType.Ok, validationResult.ErrorMessage));
				await popupAwait.Result;
				return;
			}

			var renameResult = await NginxService.RenameFileAsync(SelectedFile, $"{result.Data}.conf");
			if (!renameResult.AllOk)
			{
				var popupAwait = Modal.Show<GenericPopup>(string.Empty, new ModalParameters().Setup(PopupType.Ok, renameResult.ErrorMessage));
				await popupAwait.Result;
				return;
			}

			SelectedFile.Name = result.Data.ToString();
			SelectedFile.FullPath = renameResult.Data.FullPath;
		}

		public async Task SaveFileAsync()
		{
			var validationResult = await NginxService.ValidateForSaveFileAsync(SelectedFile);

			if (!validationResult.AllOk)
			{
				await Modal.Show<GenericPopup>(string.Empty, new ModalParameters().Setup(PopupType.Ok, validationResult.ErrorMessage)).Result;
				return;
			}

			var saveResult = await NginxService.SaveFileAsync(SelectedFile);

			if (!saveResult.AllOk)
			{
				await Modal.Show<GenericPopup>(string.Empty, new ModalParameters().Setup(PopupType.Ok, saveResult.ErrorMessage)).Result;
				return;
			}
		}

		public async Task SaveDraftFileAsync()
		{
			//var validationResult = await NginxService.ValidateForSaveDraftFileAsync(SelectedFile);

			//if (!validationResult.AllOk)
			//{
			//	await Modal.Show<GenericPopup>(string.Empty, new ModalParameters().Setup(PopupType.Ok, validationResult.ErrorMessage)).Result;
			//	return;
			//}

			var saveDraftResult = await NginxService.SaveDraftFileAsync(SelectedFile);

			if (!saveDraftResult.AllOk)
			{
				await Modal.Show<GenericPopup>(string.Empty, new ModalParameters().Setup(PopupType.Ok, saveDraftResult.ErrorMessage)).Result;
				return;
			}
		}

		public async Task TestConfiguration()
		{
			var testResult = await NginxService.TestFileAsync(SelectedFile);

			if (!testResult.AllOk)
			{
				await Modal.Show<GenericPopup>(string.Empty, new ModalParameters().Setup(PopupType.Ok, $"{testResult.ErrorMessage}, ex [{testResult.Exception.Message}]")).Result;
				return;
			}
			await Modal.Show<GenericPopup>(string.Empty, new ModalParameters().Setup(PopupType.Ok, testResult.Data)).Result;
		}

		public async Task DeleteFile()
		{
			var parameters = new ModalParameters().Setup(PopupType.YesNo, $"Are you sure you want to delete '{SelectedFile.Name}'?");

			var resultAwait = Modal.Show<GenericPopup>(string.Empty, parameters);
			var result = await resultAwait.Result;
			if ((PopupAnswer)result.Data == PopupAnswer.No) return;

			var deleteFileResult = await NginxService.DeleteFileAsync(SelectedFile);

			if (!deleteFileResult.AllOk)
			{
				var errorParameters = new ModalParameters().Setup(PopupType.Ok, $"Something went wrong, here's the error message: '{deleteFileResult.ErrorMessage}'?");
				var errorReportModalAwait = Modal.Show<GenericPopup>(string.Empty, errorParameters);
				await errorReportModalAwait.Result;
				return;
			}

			ConfigFiles.Remove(SelectedFile);
			SelectedFile = null;
		}
	}
}
