using NetinaShop.Domain.Entities.Blogs;
using NetinaShop.Domain.Entities.Users;
using System.Reflection.Metadata;
using NetinaShop.Domain.Models.Claims;

namespace NetinaShop.AdminPanel.PWA.Dialogs;

public class RoleActionDialogBoxViewModel : BaseViewModel<RoleActionRequestDto>
{
    private readonly ISnackbar _snackbar;
    private readonly IRestWrapper _restWrapper;
    private readonly IUserUtility _userUtility;
    private readonly IDialogService _dialogService;
    private readonly MudDialogInstance _mudDialog;
    

    public RoleActionDialogBoxViewModel(ISnackbar snackbar,
        IRestWrapper restWrapper,
        IUserUtility userUtility,
        IDialogService dialogService,
        MudDialogInstance mudDialog)
    {
        _snackbar = snackbar;
        _restWrapper = restWrapper;
        _userUtility = userUtility;
        _dialogService = dialogService;
        _mudDialog = mudDialog;
        ApplicationClaims.AllClaimDtos.ForEach(c => RoleClaims.Add(c));
    }

    public RoleActionDialogBoxViewModel(ISnackbar snackbar,
        IRestWrapper restWrapper,
        IUserUtility userUtility,
        IDialogService dialogService,
        MudDialogInstance mudDialog,
        ApplicationRole role)
    {
        _snackbar = snackbar;
        _restWrapper = restWrapper;
        _userUtility = userUtility;
        _dialogService = dialogService;
        _mudDialog = mudDialog;
        PageDto.RoleId = role.Id;
        IsEditing = true;

        ApplicationClaims.AllClaimDtos.ForEach(c=>RoleClaims.Add(c));
        foreach (var roleClaim in RoleClaims)
        {
            roleClaim.IsSelected = false;
        }
    }
    public bool IsEditing = false;
    public ObservableCollection<ClaimDto> RoleClaims { get; } = new ObservableCollection<ClaimDto>();



    public override async Task InitializeAsync()
    {
        if (IsEditing && PageDto.RoleId != default)
        {
            try
            {
                var token = await _userUtility.GetBearerTokenAsync();
                if (token == null)
                    throw new Exception("Token is null");
                IsProcessing = true;
                var role = await _restWrapper.RoleRestApi.ReadOne(PageDto.RoleId, token);
                PageDto = role;
                foreach (var permission in PageDto.Permissions)
                {
                    var selected = RoleClaims.FirstOrDefault(f => f.Value == permission);
                    if (selected != null)
                        selected.IsSelected = true;
                }
            }
            catch (ApiException ex)
            {
                var exe = await ex.GetContentAsAsync<ApiResult>();
                if (exe != null)
                    _snackbar.Add(exe.Message, Severity.Error);
                _snackbar.Add(ex.Content, Severity.Error);
                _mudDialog.Cancel();
            }
            catch (Exception e)
            {
                _snackbar.Add(e.Message, Severity.Error);
                _mudDialog.Cancel();
            }
            finally
            {

                IsProcessing = false;
            }
        };
    }



    public void Cancel() => _mudDialog.Cancel();

    public async Task SubmitEditAsync()
    {
        try
        {
            IsProcessing = true;
            if (PageDto.RoleId == default)
                throw new Exception("نقش اشتباه است");

            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");

            if (PageDto.PersianName.IsNullOrEmpty())
                throw new Exception("نام فارسی نقش را وارد کنید");

            if (PageDto.EnglishName.IsNullOrEmpty())
                throw new Exception("نام انگلیسی نقش را وارد کنید");

            PageDto.Permissions.Clear();
            foreach (var claimDto in RoleClaims.Where(r => r.IsSelected))
                PageDto.Permissions.Add(claimDto.Value);

            await _restWrapper.RoleRestApi.UpdateRoleAsync(PageDto, token);
            _snackbar.Add($"ویرایش بلاگ {PageDto.PersianName} با موفقیت انجام شد", Severity.Success);
            _mudDialog.Close(DialogResult.Ok(true));
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            if (exe != null)
                _snackbar.Add(exe.Message, Severity.Error);
            _snackbar.Add(ex.Content, Severity.Error);
            _mudDialog.Cancel();
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
            _mudDialog.Cancel();
        }
        finally
        {

            IsProcessing = false;
        }
    }
    public async Task SubmitCreateAsync()
    {
        try
        {
            IsProcessing = true;
            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");

            if (PageDto.PersianName.IsNullOrEmpty())
                throw new Exception("نام فارسی نقش را وارد کنید");

            if (PageDto.EnglishName.IsNullOrEmpty())
                throw new Exception("نام انگلیسی نقش را وارد کنید");
            PageDto.Permissions.Clear();
            foreach (var claimDto in RoleClaims.Where(r=>r.IsSelected))
                PageDto.Permissions.Add(claimDto.Value);

            await _restWrapper.RoleRestApi.CreateRoleAsync(PageDto, token);

            _snackbar.Add($"ساخت بلاگ {PageDto.PersianName} با موفقیت انجام شد", Severity.Success);
            _mudDialog.Close(DialogResult.Ok(true));
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            if (exe != null)
                _snackbar.Add(exe.Message, Severity.Error);
            _snackbar.Add(ex.Content, Severity.Error);
            _mudDialog.Cancel();
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
            _mudDialog.Cancel();
        }
        finally
        {

            IsProcessing = false;
        }
    }
}