@page "/Profile"
@page "/Profile/{from}"
@using Front.Services
@using Shared.DTOs
@layout PanelLayout
@inject UserAuthenticationDTO userinfo
@inject HttpClientController _hc
@inject ILocalStorageService Storage;
<PageTitle>پروفایل</PageTitle>
<div class="container-xxl flex-grow-1 container-p-y">
    <h4 class="fw-bold py-3 mb-4">
        <span class="text-muted fw-light">متفرقه /</span> پروفایل
    </h4>
    <div class="row">
        <div class="col-md-10">
        <Alert hidden="@Hidealert" Color="@alertColor" Dismissable="false">
            <Icon Name="@alertIconName" class="me-2"></Icon>
            @alertMessage
        </Alert>
        </div>

        <div class="col-md-2">
            <Spinner Visible="SpinnerVisible" Color="SpinnerColor.Primary" />
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="card mb-4">
                <h5 class="card-header">تغییر عکس</h5>
                <div class="card-body">
                    <div class="d-flex align-items-start align-items-sm-center gap-4">
                        @{
                             _src = "assets/img/avatars/2.png";
                            if (userinfo.Company.Logo != null)
                                _src = "data:image/jpeg;base64," + @userinfo.Company.Logo;

                        }
                        <img src="@_src" alt="user-avatar" class="d-block rounded" height="200" width="200" id="uploadedAvatar">
                        <div class="button-wrapper">
                            <label for="upload" class="btn btn-primary me-2 mb-4" tabindex="0">
                                <span class="d-none d-sm-block">آپلود تصویر جدید</span>
                                <i class="bx bx-upload d-block d-sm-none"></i>
                                <InputFile  OnChange="changePic" type="file" id="upload" class="account-file-input" hidden="" accept="image/png, image/jpeg"/>
                            </label>

                            <p class="text-muted mb-0">JPG، GIF یا PNG مجاز است. حداکثر اندازه 3 مگابایت</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-6">
            <div class="card mb-4">
                <h5 class="card-header">تغییر کلمه عبور</h5>
                <div class="card-body">
                    <EditForm Model="changepassModel" OnSubmit="changepassSubmit" FormName="changepass">
                        <div class="mb-3 row">
                            <label for="defaultFormControlInput" class="form-label">کلمه عبور فعلی</label>
                            <div class="col-md-10">
                                <InputText @bind-Value="@changepassModel.oldPass" style="text-align:center;" class="form-control" type="password" id="html5-password-input1"/>
                            </div>
                        </div>
                        <div class="mb-3 row">
                            <label for="defaultFormControlInput" class="form-label">کلمه عبور جدید</label>
                            <div class="col-md-10">
                                <InputText style="text-align:center;" @bind-Value="@changepassModel.newPass" class="form-control" type="password" id="html5-password-input2" />
                            </div>
                        </div>
                        <div class="mb-3 row">
                            <label for="defaultFormControlInput" class="form-label">تکرار کلمه عبور جدید</label>
                            <div class="col-md-10">
                                <InputText @bind-Value="@changepassModel.renewPass" style="text-align:center;" class="form-control" type="password" id="html5-password-input3" />
                            </div>
                        </div>
                        <Button Disabled="SpinnerVisible" Type="ButtonType.Submit" Color="ButtonColor.Primary">ارسال</Button>
                    </EditForm>
          
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card mb-4">
                <h5 class="card-header">تغییر نام کاربری/ موبایل</h5>
                <div class="card-body">
                    <EditForm Model="newUsername" OnSubmit="changeUserNameSubmit" FormName="changeUsername">
                        <div class="mb-3 row">
                            <label for="defaultFormControlInput" class="form-label">موبایل جدید</label>
                            <div class="input-group input-group-merge">
                                <InputText @bind-Value="@newUsername" type="text" style="text-align:left;" id="basic-icon-default-phone" class="form-control phone-mask" placeholder="0000 000 0911" aria-label="0000 000 0911"  aria-describedby="basic-icon-default-phone2"/>
                                <span id="basic-icon-default-phone2" class="input-group-text"><i class="bx bx-phone"></i></span>
                            </div>
                        </div>
                        <Button Disabled="SpinnerVisible" Type="ButtonType.Submit" Color="ButtonColor.Primary">ارسال</Button>
                       </EditForm>

                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-6">
            <div class="card mb-4">
                <h5 class="card-header">تغییر نام</h5>
                <div class="card-body">
                    <EditForm Model="newname" OnSubmit="changeNameSubmit" FormName="changename">
                        <div class="mb-3 row">
                            <label for="defaultFormControlInput" class="form-label">نام جدید</label>
                            <div class="input-group input-group-merge">
                                <span id="basic-icon-default-company2" class="input-group-text"><i class="bx bx-buildings"></i></span>
                                  <InputText @bind-Value="@newname"  style="text-align:right;" type="text" id="basic-icon-default-company" class="form-control" placeholder="@userinfo.Company.Name" aria-label="@userinfo.Company.Name" aria-describedby="basic-icon-default-company2"/>
                            </div>
                        </div>
                        <Button Disabled="SpinnerVisible" Type="ButtonType.Submit" Color="ButtonColor.Primary">ارسال</Button>
                    </EditForm>
                </div>
            </div>
        </div>
       
    </div>
</div>



@code {
    public bool SpinnerVisible { get; set; } = false;
    [Parameter]
    public string from { get; set; } = "";

    public string _src { get; set; }

    //3m
    private long maxFileSize = 3145710;
    [SupplyParameterFromForm]
    public ChangePasswordDto changepassModel { get; set; }
    [SupplyParameterFromForm]
    public string newUsername { get; set; } 
    [SupplyParameterFromForm]
    public string newname { get; set; }
    // alert
    AlertColor alertColor = AlertColor.Primary;
    IconName alertIconName = IconName.CheckCircleFill;
    bool Hidealert = true;
    string alertMessage = "";
    protected override async Task OnParametersSetAsync()
    {
        if (from == "Verification")
        {
            ShowSuccessAlert("تغییر کاربری با موفقیت انجام شد");
        }

        await base.OnParametersSetAsync();
    }
    protected override void OnInitialized()
    {
        newname ??= userinfo.Company.Name;
        newUsername ??= userinfo.UserName;
        changepassModel ??= new();
    } 
}
@functions{
    private void ShowDangerAlert(string msg)
    {
        Hidealert = false;
        alertColor = AlertColor.Danger;
        alertIconName = IconName.ExclamationTriangleFill;
        alertMessage = msg;
    }
    private void ShowSuccessAlert(string msg)
    {
        Hidealert = false;
        alertColor = AlertColor.Success;
        alertIconName = IconName.CheckCircleFill;
        alertMessage = msg;
    }
    private async Task changepassSubmit(){
        SpinnerVisible = true;
        var request = await _hc.Post<ChangePasswordDto>("User/ChangePassword", changepassModel);
        if (request.IsSuccessStatusCode)
        {
            if (await request.Content.ReadFromJsonAsync<bool>())
            {
                _hc._hc.DefaultRequestHeaders.Clear();
                await Storage.RemoveItem("token");
                userinfo.Token = "";
                _hc._nav.NavigateTo("/Sign-in/changePass");
            }
            else ShowDangerAlert("خطای سیستمی");
        }else
        {
            var errors = await request.Content.ReadFromJsonAsync<List<string>>();
            ShowDangerAlert(errors[0]);
        }
        SpinnerVisible = false;
    }
    private async Task changeUserNameSubmit()
    {
        SpinnerVisible = true;
        if (newUsername != userinfo.UserName)
        {
            var request = await _hc.Get($"User/ChangeUserName/{newUsername}");
            if (request.IsSuccessStatusCode)
            {
                var VerificationID = await request.Content.ReadFromJsonAsync<int>();
                _hc._nav.NavigateTo($"Verification/{VerificationID}");


            }
            else
            {
                var errors = await request.Content.ReadFromJsonAsync<List<string>>();
                ShowDangerAlert(errors[0]);
            }
        }
        SpinnerVisible = false;
    }
    private async Task changeNameSubmit()
    {
        SpinnerVisible = true;
        if (newname != userinfo.Company.Name)
        {
            var request = await _hc.Get($"Company/ChangeName/{newname}");
            if (request.IsSuccessStatusCode)
            {
                if (await request.Content.ReadFromJsonAsync<bool>())
                {
                    userinfo.FullName= userinfo.Company.Name = newname;
                    ShowSuccessAlert("تغییر نام با موفقیت انجام شد");

                }
               else
                {
                    ShowDangerAlert("خطایی در اجرای عملیات رخ داده");
                }


            }
            else
            {
                var errors = await request.Content.ReadFromJsonAsync<List<string>>();
                ShowDangerAlert(errors[0]);
            }
        }
        SpinnerVisible = false;
    }
    private async Task changePic(InputFileChangeEventArgs e){
        SpinnerVisible = true;
        if (e.GetMultipleFiles()[0].Size <= maxFileSize)
        {
            string Base64Str = "";
            byte[] Array;
            using (MemoryStream stream = new MemoryStream())
            {
                await e.GetMultipleFiles()[0].OpenReadStream(maxFileSize).CopyToAsync(stream);

                Array = stream.ToArray();
                Base64Str = Convert.ToBase64String(Array);

            }

            if (!string.IsNullOrEmpty(Base64Str))
            {
                var request = await _hc.Post<byte[]>("Company/ChangeLogo", Array);
                if (request.IsSuccessStatusCode)
                {
                    userinfo.Company.Logo = _src = Base64Str;
                 
                    ShowSuccessAlert("تصویر با موفقیت تغییر کرد");
                }
                else
                {
                    ShowDangerAlert( "خطایی در اجرای عملیات رخ داده");
                }
            }
        }
        else
        {
            ShowDangerAlert ( "حجم فایل بیشتر از حد مجاز می باشد");
        }
        SpinnerVisible = false;
    }

}