@namespace Oqtane.Modules.Admin.RecycleBin
@inherits ModuleBase
@inject NavigationManager NavigationManager
@inject IPageModuleService PageModuleService
@inject IModuleService ModuleService
@inject IPageService PageService
@inject IStringLocalizer<Index> Localizer
@inject IStringLocalizer<SharedResources> SharedLocalizer

@if (_pages == null || _modules == null)
{
    <p><em>@SharedLocalizer["Loading"]</em></p>
}
else
{
	<TabStrip>
		<TabPanel Name="Pages" ResourceKey="Pages" Heading="Pages">
			@if (!_pages.Where(item => item.IsDeleted).Any())
			{
				<br />
				<p>@Localizer["NoPage.Deleted"]</p>
			}
			else
			{
          <Pager Items="@_pages.Where(item => item.IsDeleted)" CurrentPage="@_pagePage.ToString()" OnPageChange="OnPageChangePage">
					<Header>
						<th style="width: 1px;">&nbsp;</th>
						<th style="width: 1px;">&nbsp;</th>
						<th>@SharedLocalizer["Name"]</th>
						<th>@Localizer["DeletedBy"]</th>
						<th>@Localizer["DeletedOn"]</th>
					</Header>
					<Row>
                        <td><button type="button" @onclick="@(() => RestorePage(context))" class="btn btn-success" title="Restore">@Localizer["Restore"]</button></td>
						<td><ActionDialog Header="Delete Page" Message="@string.Format(Localizer["Confirm.Page.Delete"], context.Name)" Action="Delete" Security="SecurityAccessLevel.Admin" Class="btn btn-danger" OnClick="@(async () => await DeletePage(context))" ResourceKey="DeletePage" /></td>
						<td>@context.Name</td>
						<td>@context.DeletedBy</td>
						<td>@context.DeletedOn</td>
					</Row>
				</Pager>
				<br />
				<ActionDialog Header="Remove All Deleted Pages" Message="Are You Sure You Wish To Permanently Remove All Deleted Pages?" Action="Remove All Deleted Pages" Security="SecurityAccessLevel.Admin" Class="btn btn-danger" OnClick="@(async () => await DeleteAllPages())" ResourceKey="DeleteAllPages" />
			}
		</TabPanel>
		<TabPanel Name="Modules" ResourceKey="Modules" Heading="Modules">
			@if (!_modules.Where(item => item.IsDeleted).Any())
			{
				<br />
				<p>@Localizer["NoModule.Deleted"]</p>
			}
			else
			{
          <Pager Items="@_modules.Where(item => item.IsDeleted)" CurrentPage="@_pageModule.ToString()" OnPageChange="OnPageChangeModule">
					<Header>
						<th style="width: 1px;">&nbsp;</th>
						<th style="width: 1px;">&nbsp;</th>
						<th>@Localizer["Page"]</th>
						<th>@Localizer["Module"]</th>
						<th>@Localizer["DeletedBy"]</th>
						<th>@Localizer["DeletedOn"]</th>
					</Header>
					<Row>
						<td><button type="button" @onclick="@(() => RestoreModule(context))" class="btn btn-success" title="Restore">@Localizer["Restore"]</button></td>
						<td><ActionDialog Header="Delete Module" Message="@string.Format(Localizer["Confirm.Module.Delete"], context.Title)" Action="Delete" Security="SecurityAccessLevel.Admin" Class="btn btn-danger" OnClick="@(async () => await DeleteModule(context))" ResourceKey="DeleteModule" /></td>
						<td>@_pages.Find(item => item.PageId == context.PageId).Name</td>
						<td>@context.Title</td>
						<td>@context.DeletedBy</td>
						<td>@context.DeletedOn</td>
					</Row>
				</Pager>
				<br />
				<ActionDialog Header="Remove All Deleted Modules" Message="Are You Sure You Wish To Permanently Remove All Deleted Modules?" Action="Remove All Deleted Modules" Security="SecurityAccessLevel.Admin" Class="btn btn-danger" OnClick="@(async () => await DeleteAllModules())" ResourceKey="DeleteAllModules" />
			}
		</TabPanel>
	</TabStrip>
}

@code {
	private List<Page> _pages;
	private List<Module> _modules;
    private int _pagePage = 1;
    private int _pageModule = 1;
    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Admin;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            await Load();
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Loading Deleted Pages Or Modules {Error}", ex.Message);
            AddModuleMessage(Localizer["Error.DeletedModulePage.Load"], MessageType.Error);
        }
    }

    private async Task Load()
    {
        _pages = await PageService.GetPagesAsync(PageState.Site.SiteId);
        _modules = await ModuleService.GetModulesAsync(PageState.Site.SiteId);
    }

    private async Task RestorePage(Page page)
    {
        try
        {
            page.IsDeleted = false;
            await PageService.UpdatePageAsync(page);
            await logger.LogInformation("Page Restored {Page}", page);
            await Load();
            StateHasChanged();
            NavigationManager.NavigateTo(NavigateUrl());
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Restoring Deleted Page {Page} {Error}", page, ex.Message);
            AddModuleMessage(Localizer["Error.Page.Restore"], MessageType.Error);
        }
    }

    private async Task DeletePage(Page page)
    {
        try
        {
            await PageService.DeletePageAsync(page.PageId);
            await logger.LogInformation("Page Permanently Deleted {Page}", page);
            await Load();
            StateHasChanged();
            NavigationManager.NavigateTo(NavigateUrl());
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Permanently Deleting Page {Page} {Error}", page, ex.Message);
            AddModuleMessage(ex.Message, MessageType.Error);
        }
    }

    private async Task DeleteAllPages()
    {
        try
        {
            ShowProgressIndicator();
            foreach (Page page in _pages.Where(item => item.IsDeleted))
            {
                await PageService.DeletePageAsync(page.PageId);
                await logger.LogInformation("Page Permanently Deleted {Page}", page);
            }

            await logger.LogInformation("Pages Permanently Deleted");
            await Load();
            HideProgressIndicator();
            StateHasChanged();
            NavigationManager.NavigateTo(NavigateUrl());
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Permanently Deleting Pages {Error}", ex.Message);
            AddModuleMessage(ex.Message, MessageType.Error);
            HideProgressIndicator();
        }
    }

    private async Task RestoreModule(Module module)
    {
        try
        {
            var pagemodule = await PageModuleService.GetPageModuleAsync(module.PageModuleId);
            pagemodule.IsDeleted = false;
            await PageModuleService.UpdatePageModuleAsync(pagemodule);
            await logger.LogInformation("Module Restored {Module}", module);
            await Load();
            StateHasChanged();
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Restoring Deleted Module {Module} {Error}", module, ex.Message);
            AddModuleMessage(Localizer["Error.Module.Restore"], MessageType.Error);
        }
    }

    private async Task DeleteModule(Module module)
    {
        try
        {
            await PageModuleService.DeletePageModuleAsync(module.PageModuleId);
            await logger.LogInformation("Module Permanently Deleted {Module}", module);
            await Load();
            StateHasChanged();
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Permanently Deleting Module {Module} {Error}", module, ex.Message);
            AddModuleMessage(Localizer["Error.Module.Delete"], MessageType.Error);
        }
    }

    private async Task DeleteAllModules()
    {
        try
        {
            ShowProgressIndicator();
            foreach (Module module in _modules.Where(item => item.IsDeleted).ToList())
            {
                await PageModuleService.DeletePageModuleAsync(module.PageModuleId);
            }
            await logger.LogInformation("Modules Permanently Deleted");
            await Load();
            HideProgressIndicator();
            StateHasChanged();
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Permanently Deleting Modules {Error}", ex.Message);
            AddModuleMessage(Localizer["Error.Modules.Delete"], MessageType.Error);
            HideProgressIndicator();
        }
    }
    private void OnPageChangePage(int page)
    {
        _pagePage = page;
    }
    private void OnPageChangeModule(int page)
    {
        _pageModule = page;
    }
}
