@namespace Oqtane.Modules.Admin.ModuleDefinitions
@inherits ModuleBase
@inject NavigationManager NavigationManager
@inject IModuleDefinitionService ModuleDefinitionService
@inject IPackageService PackageService
@inject IStringLocalizer<Index> Localizer
@inject IStringLocalizer<SharedResources> SharedLocalizer

@if (_moduleDefinitions == null)
{
    <p><em>@SharedLocalizer["Loading"]</em></p>
}
else
{
	<div class="container">
		<div class="row mb-3 align-items-center">
			<div class="col-sm-6">
				<ActionLink Action="Add" Text="Install Module" ResourceKey="InstallModule" />
				@((MarkupString)"&nbsp;")
				<ActionLink Action="Create" Text="Create Module" ResourceKey="CreateModule" Class="btn btn-secondary" />
			</div>
			<div class="col-sm-6">
				<select class="form-select" @onchange="(e => CategoryChanged(e))">
					@foreach (var category in _categories)
					{
						if (category == _category)
						{
							<option value="@category" selected>@category @Localizer["Modules"]</option>
						}
						else
						{
							<option value="@category">@category @Localizer["Modules"]</option>
						}
					}
				</select>
			</div>
		</div>
	</div>
			
	<Pager Items="@_moduleDefinitions">
        <Header>
            <th style="width: 1px;">&nbsp;</th>
            <th style="width: 1px;">&nbsp;</th>
            <th>@SharedLocalizer["Name"]</th>
            <th>@SharedLocalizer["Version"]</th>
            <th>@Localizer["Enabled"]</th>
            <th>@Localizer["InUse"]</th>
            <th>@SharedLocalizer["Support"]</th>
            <th>@SharedLocalizer["Expires"]</th>
            <th style="width: 1px;">&nbsp;</th>
        </Header>
        <Row>
            <td><ActionLink Action="Edit" Parameters="@($"id=" + context.ModuleDefinitionId.ToString())" ResourceKey="EditModule" /></td>
            <td>
                @if (context.AssemblyName != Constants.ClientId)
                {
                    <ActionDialog Header="Delete Module" Message="@string.Format(Localizer["Confirm.Module.Delete", context.Name])" Action="Delete" Security="SecurityAccessLevel.Host" Class="btn btn-danger" OnClick="@(async () => await DeleteModule(context))" ResourceKey="DeleteModule" />
                }
            </td>
            <td>@context.Name</td>
            <td>@context.Version</td>
            <td>
               @if (context.IsEnabled)
               {
                   <span>@SharedLocalizer["Yes"]</span>
               }
               else
               {
                   <span>@SharedLocalizer["No"]</span>
               }
            </td>
            <td>
				@if (context.AssemblyName == Constants.ClientId || PageState.Modules.Where(m => m.ModuleDefinition?.ModuleDefinitionId == context.ModuleDefinitionId).FirstOrDefault() != null)
                {
                    <span>@SharedLocalizer["Yes"]</span>
                }
                else
                {
                    <span>@SharedLocalizer["No"]</span>
                }
            </td>
            <td>
                @((MarkupString)SupportLink(context.PackageName, context.Version))
            </td>
            <td>
                @((MarkupString)PurchaseLink(context.PackageName))
            </td>
            <td>
				@{ 
					var version = UpgradeAvailable(context.PackageName, context.Version);
				} 
                @if (version != context.Version)
                {
                    <button type="button" class="btn btn-success" @onclick=@(async () => await DownloadModule(context.PackageName, version))>@SharedLocalizer["Upgrade"]</button>
                }
            </td>
        </Row>
    </Pager>
}

@code {
    private List<ModuleDefinition> _allModuleDefinitions;
    private List<ModuleDefinition> _moduleDefinitions;
    private List<Package> _packages;
    private List<string> _categories = new List<string>();
    private string _category = "Common";

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Host;

    protected override async Task OnParametersSetAsync()
    {
        try
        {
            _allModuleDefinitions = await ModuleDefinitionService.GetModuleDefinitionsAsync(PageState.Site.SiteId);
            _categories = _allModuleDefinitions.SelectMany(m => m.Categories.Split(',')).Distinct().ToList();
            await LoadModuleDefinitions();
        }
        catch (Exception ex)
        {
            if (_moduleDefinitions == null)
            {
                await logger.LogError(ex, "Error Loading Modules {Error}", ex.Message);
                AddModuleMessage(Localizer["Error.Module.Load"], MessageType.Error);
            }
        }
    }

    private async Task LoadModuleDefinitions()
    {
        _moduleDefinitions = _allModuleDefinitions.Where(item => item.Categories.Contains(_category)).ToList();
        _packages = await PackageService.GetPackageUpdatesAsync("module");
    }

    private string PurchaseLink(string packagename)
    {
        string link = "";
        if (!string.IsNullOrEmpty(packagename) && _packages != null)
        {
            var package = _packages.Where(item => item.PackageId == packagename).FirstOrDefault();
            if (package != null)
            {
                if (package.ExpiryDate != null && package.ExpiryDate.Value.Date != DateTime.MaxValue.Date)
                {
                    if (string.IsNullOrEmpty(package.PaymentUrl))
                    {
                        link = "<span>" + package.ExpiryDate.Value.Date.ToString("MMM dd, yyyy") + "</span>";
                    }
                    else
                    {
                        link = "<a class=\"btn btn-primary\" style=\"text-decoration: none !important\" href=\"" + package.PaymentUrl + "\" target=\"_new\">" + package.ExpiryDate.Value.Date.ToString("MMM dd, yyyy") + "</a>";
                    }
                }
			}
		}
		return link;
	}

    private string SupportLink(string packagename, string version)
    {
        string link = "";
        if (!string.IsNullOrEmpty(packagename) && _packages != null)
        {
            var package = _packages.Where(item => item.PackageId == packagename).FirstOrDefault();
            if (package != null && !string.IsNullOrEmpty(package.SupportUrl))
            {
                link += "<a class=\"btn btn-info\" style=\"text-decoration: none !important\" href=\"" + package.SupportUrl.Replace("{Version}", version) + "\" target=\"_new\">" + SharedLocalizer["Help"] + "</a>";
            }
        }
        return link;
    }

	private string UpgradeAvailable(string packagename, string version)
	{
		if (!string.IsNullOrEmpty(packagename) && _packages != null)
		{
			var package = _packages.Where(item => item.PackageId == packagename).FirstOrDefault();
			if (package != null && Version.Parse(package.Version).CompareTo(Version.Parse(version)) > 0)
			{
				return package.Version;
			}
		}
		return version;
	}

	private async Task DownloadModule(string packagename, string version)
	{
		try
		{
			await PackageService.DownloadPackageAsync(packagename, version);
			await logger.LogInformation("Module Downloaded {ModuleDefinitionName} {Version}", packagename, version);
			AddModuleMessage(string.Format(Localizer["Success.Module.Install"], NavigateUrl("admin/system")), MessageType.Success);
		}
		catch (Exception ex)
		{
			await logger.LogError(ex, "Error Downloading Module {ModuleDefinitionName} {Version} {Error}", packagename, version, ex.Message);
			AddModuleMessage(Localizer["Error.Module.Download"], MessageType.Error);
		}
	}

	private async Task DeleteModule(ModuleDefinition moduleDefinition)
	{
		try
		{
			await ModuleDefinitionService.DeleteModuleDefinitionAsync(moduleDefinition.ModuleDefinitionId, moduleDefinition.SiteId);
			AddModuleMessage(Localizer["Success.Module.Delete"], MessageType.Success);
			NavigationManager.NavigateTo(NavigateUrl(PageState.Page.Path, true));
		}
		catch (Exception ex)
		{
			await logger.LogError(ex, "Error Deleting Module {ModuleDefinition} {Error}", moduleDefinition, ex.Message);
			AddModuleMessage(Localizer["Error.Module.Delete"], MessageType.Error);
		}
	}

	private async Task CategoryChanged(ChangeEventArgs e)
	{
		_category = (string)e.Value;
        await LoadModuleDefinitions();
	}
}
