@using Components
@using Newtonsoft.Json
@using Models.Identity
@inject ILoadingSpinner _LoadingSpinner
@inherits LayoutComponentBase

<RoundContainerContainer Padding="0" Scroll=true>
    <style>
        div.scroll-div {
            background-color: #F1F1F1;
            overflow-y: hidden;
            height: calc(100vh - 122px)
        }

        @@media only screen and (min-width: 600px) {

            div.scroll-div {
                height: calc(100vh - 120px)
            }
        }
    </style>
    <div class="@BT.FlexJustifyAround" style="flex-direction:column" @onclick="@(()=>ToggleMenu(close:true))">
        @*Top Header*@
        <div class="@BT.Row @BT.Background(ColorType.white) @BT.Margin(0) @BT.Padding(2) @BT.SmallShadow" style="height:60px;">
            <div style="@Styles.VerticalSelfAlign(TextAlignment.center)" class="@BT.Col(6) @BT.TextAlign(TextAlignment.left)">
                <img role="button" @onclick="@(()=>ToggleMenu(close:false))" src="/assets/images/Hamburger_icon.svg" width="30">

                <img src="/assets/images/logo-blue.png" alt="" width="60">
            </div>

            <div class="@BT.Col(6) @BT.TextAlign(TextAlignment.right)">
            </div>
        </div>
        @*end of Top Header*@
        <div class="scroll-div @BT.Row @BT.Margin(0) @BT.DisplayBlock">
            @Body
        </div>
        @*Footer*@
        <div class="@BT.Background(ColorType.white) @(BT.Row) @(BT.TextAlign(TextAlignment.center)) @(BT.SmallShadow) "
             style="height:60px;font-size:12px;width:100%;margin:0 auto;">

            <div @onclick="@(()=>NavManager.NavigateTo("/dashboard"))" role="button" style="@(Styles.VerticalSelfAlign(TextAlignment.center)) " class="@(BT.Col(4)) @(BT.TextAlign(TextAlignment.right))">
                <img src="/assets/images/ico-dashboard.png" alt="" width="26">
                <br />
                داشبورد
            </div>
            <div @onclick="@(()=>NavManager.NavigateTo("/Suit/Subject/Level1"))" role="button" style="@(Styles.VerticalSelfAlign(TextAlignment.center))" class="@(BT.Col(4)) @(BT.TextAlign(TextAlignment.right))">
                <img src="/assets/images/ico-add.png" alt="" width="26">
                <br />
                دعوی جدید
            </div>

            <div role="button" style="@(Styles.VerticalSelfAlign(TextAlignment.center))" class="@(BT.Col(4)) @(BT.TextAlign(TextAlignment.right))">
                <img src="/assets/images/ico-user.png" alt="" width="26">
                <br />
                پروفایل
            </div>

        </div>
        @*End Of Footer*@

    </div>

    <div class="menu  @(BT.Background(ColorType.dark))  @BT.Position(Postion.Position_Fixed)"
         style="top:auto;height:100vh;top:0;width:@(MenuWidth)%;max-width:450px;">
        @if (!MenuIsChanging && MenuWidth > 10)
        {
            <a href="/about">درباره حق‌تو</a>
            <a href="/Privacy">حریم ‌خصوصی</a>
            <a href="/Contact">تماس با ما</a>


        }
    </div>
</RoundContainerContainer>
<style>
    div.menu a {
        line-height: 1.5em;        
        padding:10px;
        border-bottom: 1px white solid;
        width: 100%;
        text-decoration: none;
        font-size: 1.5em;
        opacity: 1;
        color: white;
        display: block;
    }
</style>
@code
{
    public int MenuWidth { set; get; } = 0;
    public bool ShowMenu { set; get; } = false;
    public bool MenuIsChanging { set; get; } = false;
    protected async Task ToggleMenu(bool close = false)
    {
        if (MenuIsChanging)
            return;
        MenuIsChanging = true;
        if (close)
        {
            Console.WriteLine("closing menu");
            while (MenuWidth > 0)
            {
                MenuWidth = Math.Max(MenuWidth -= 2, 0);
                StateHasChanged();
                await Task.Delay(5);
            }
            MenuIsChanging = false;
            return;
        }
        else
        {
            Console.WriteLine("opening menu");
            while (MenuWidth < 60)
            {
                Console.WriteLine(MenuWidth);
                MenuWidth = Math.Min(MenuWidth += 2, 60);
                StateHasChanged();
                await Task.Delay(5);
            }
            MenuIsChanging = false;

        }
    }

    protected override async void OnAfterRender(bool firstRender)
    {
        if (firstRender)
            await CheckLogin();
        base.OnAfterRender(firstRender);
        NavManager.LocationChanged += HideMenu;
    }
    private void HideMenu(object sender, LocationChangedEventArgs e)
    {
        MenuWidth = 0;
        StateHasChanged();
    }
    async Task CheckLogin()
    {
        Console.WriteLine("" + Statics.LastCheck);
        if (Statics.LastCheck.HasValue && DateTime.Now.Subtract(Statics.LastCheck.Value).TotalMinutes < 5)
        {
            Console.WriteLine("less than 5 minutes login check");
            base.OnInitialized();
            return;
        }
        Console.WriteLine("checking login...");
        Statics.LastCheck = DateTime.Now;
        var hasToken = await LocalStorage.ContainKeyAsync(Statics.LoginTokenKey);
        if (!hasToken)
            NavManager.NavigateTo("/");
        else
        {
            var token = await LocalStorage.GetItemAsStringAsync(Statics.LoginTokenKey);
            var res = await _userUtils.CheckLogin();

            if (res.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                var refreshRes = await _userUtils.RefreshToken(new RefreshTokenModel
                    {
                        Token = token
                    });
                if (refreshRes.IsSuccessStatusCode)
                {
                    var newToken = JsonConvert.DeserializeObject<PlainToken>(await refreshRes.Content.ReadAsStringAsync());
                    Statics.LoginTokenKey = newToken.AccessToken;
                    Statics.RefreshTokenKey = newToken.RefreshToken;
                    await LocalStorage.SetItemAsync(Statics.LoginTokenKey, Statics.LoginTokenKey);
                    await LocalStorage.SetItemAsync(Statics.RefreshTokenKey, Statics.RefreshTokenKey);
                }
            }
            if (!res.IsSuccessStatusCode)
            {
                await _LoadingSpinner.HideLoading();
                await _sweetAlertService.ShowSwal(title: "", message: "نشست منقضی شد،لطفا مجددا وارد شوید", SweetAlertIcon.Error);
                NavManager.NavigateTo("/login");
            }
            else
            {
                var result =
                JsonConvert.DeserializeObject<CheckLoginResponse>(
                    await res.Content.ReadAsStringAsync());
                Statics.CurrentLoginInfo = result;
            }
            await _LoadingSpinner.HideLoading();
            StateHasChanged();
        }
    }

    private async void SignOut()
    {
        await LocalStorage.RemoveItemAsync(Statics.LoginTokenKey);
        await LocalStorage.RemoveItemAsync(Statics.RefreshTokenKey);
        NavManager.NavigateTo("/login");
    }

}
