using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Routing;

using Front.Program.Views.Project;
using Front.Program.Views.Academy;
using Front.Program.Services;
using Front.Program.ViewModels;

namespace Front.Program.Layout;

public partial class MainLayout : LayoutComponentBase, IDisposable
{
    [Inject] NavigationManager Navigation { get; set; } = default!;
    [Inject] LoadingService LoadingService { get; set; } = default!;
    [Inject] UserStateService UserStateService { get; set; } = default!;

    // 경로의 시작 부분
    // protected bool isHidePrjTop => Navigation.ToBaseRelativePath(Navigation.Uri).StartsWith("auth", StringComparison.OrdinalIgnoreCase);
    protected bool isIntro => Navigation.ToBaseRelativePath(Navigation.Uri).StartsWith("am/intro", StringComparison.OrdinalIgnoreCase)
                              || Navigation.ToBaseRelativePath(Navigation.Uri).StartsWith("/", StringComparison.OrdinalIgnoreCase);
    
    // 경로의 끝 부분
    protected bool isHidePrjTop => Navigation.ToBaseRelativePath(Navigation.Uri).EndsWith("auth", StringComparison.OrdinalIgnoreCase);
    protected bool isAcademy => Navigation.ToBaseRelativePath(Navigation.Uri).StartsWith("am", StringComparison.OrdinalIgnoreCase);
    
    // 경로 일치
    // protected bool isIntro => Navigation.ToBaseRelativePath(Navigation.Uri).Equals("am/intro", StringComparison.OrdinalIgnoreCase);
    
    protected override async Task OnInitializedAsync()
    {
        LoadingService.OnChange += StateHasChanged;
        Navigation.LocationChanged += HandleLocationChanged;
        HandleLocationChanged(this, new LocationChangedEventArgs(Navigation.Uri, false));
        if (isAcademy)
        {
            if(!UserStateService.isLogin || UserStateService.UserData == null)
            {
                LoggerService.Write("로그인 상태가 아닙니다. 초기로 돌립니다.");
                if (isIntro)
                {
                } //await UserStateService.ClearUserStateAsnyc(); 
                else
                {
                    await UserStateService.ClearUserStateAsnyc();
                    Navigation.NavigateTo("/");
                }
            }
        }
    }

    // 페이지의 URL이 변경될 때마다 실행되는 이벤트 핸들러
    private async void HandleLocationChanged(object? sender, LocationChangedEventArgs e)
    {
        LoadingService.HideNavigationLoading();
    }

    public void Dispose()
    {
        LoadingService.OnChange -= StateHasChanged;
        Navigation.LocationChanged -= HandleLocationChanged;
    }
}