namespace Netina.AdminPanel.PWA.Pages;

public class MarketerManagementPageViewModel : BaseViewModel<MarketerSetting>
{
    private readonly NavigationManager _navigationManager;
    private readonly ISnackbar _snackbar;
    private readonly IUserUtility _userUtility;
    private readonly IDialogService _dialogService;
    private readonly IRestWrapper _restWrapper;


    public MarketerManagementPageViewModel(NavigationManager navigationManager, ISnackbar snackbar, IUserUtility userUtility, IRestWrapper restWrapper, IDialogService dialogService) : base(userUtility)
    {
        _navigationManager = navigationManager;
        _snackbar = snackbar;
        _userUtility = userUtility;
        _restWrapper = restWrapper;
        _dialogService = dialogService;
    }
    public override async Task InitializeAsync()
    {
        try
        {
            IsProcessing = true;
            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null)
                throw new Exception("Token is null");

            PageDto = await _restWrapper.SettingRestApi.GetSettingAsync<MarketerSetting>("MarketerSetting", token);


        }
        catch (ApiException e)
        {
            var exe = await e.GetContentAsAsync<ApiResult>();
            _snackbar.Add(exe != null ? exe.Message : e.Content, Severity.Error);
        }
        catch (Exception ex)
        {
            _snackbar.Add(ex.Message, Severity.Error);
        }
        finally
        {
            IsProcessing = false;
        }

        await base.InitializeAsync();
    }


    public async Task SubmitSettingAsync()
    {
        try
        {

            var token = await _userUtility.GetBearerTokenAsync();
            if (token == null) throw new Exception("Token is null");
            await _restWrapper.SettingRestApi.PostSettingAsync("MarketerSetting", PageDto, token);
            _snackbar.Add("تنظیمات بازاریاب ها با موفقیت به روز شد", Severity.Success);
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            _snackbar.Add(exe != null ? exe.Message : ex.Content, Severity.Error);
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
        }
        finally
        {
            IsProcessing = false;
        }

    }
}