using MudBlazor;
using Netina.AdminPanel.PWA.Services.RestServices;

namespace Netina.AdminPanel.PWA.Dialogs;

public class ReviewActionDialogBoxViewModel : BaseViewModel<CommentSDto>
{

    private readonly ISnackbar _snackbar;
    private readonly IRestWrapper _restWrapper;
    private readonly IDialogService _dialogService;
    private readonly MudDialogInstance _mudDialog;

    public ReviewActionDialogBoxViewModel(ISnackbar snackbar,
        IRestWrapper restWrapper,
        IUserUtility userUtility,
        IDialogService dialogService,
        MudDialogInstance mudDialog) : base(userUtility)
    {
        _snackbar = snackbar;
        _restWrapper = restWrapper;
        _dialogService = dialogService;
        _mudDialog = mudDialog;
    }
    public ReviewActionDialogBoxViewModel(ISnackbar snackbar,
        IRestWrapper restWrapper,
        IUserUtility userUtility,
        IDialogService dialogService,
        MudDialogInstance mudDialog,
        CommentSDto review) : base(userUtility)
    {
        _snackbar = snackbar;
        _restWrapper = restWrapper;
        _dialogService = dialogService;
        _mudDialog = mudDialog;
        Review = review;
        PageDto = Review;
    }

    private CommentSDto? _review = null;
    public CommentSDto? Review
    {
        get => _review;
        set
        {
            _review = value;
            if (_review != null)
            {
                IsEditing = true;
            }
        }
    }

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

    public bool IsEditing = false;
    public string AnswerContent { get; set; } = string.Empty;
    public async Task SubmitAnswer()
    {

        try
        {
            IsProcessing = true;

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

            await _restWrapper.ReviewRestApi.CreateAsync(new CreateCommentCommand($"پاسخ به نظر - {PageDto.Title}", AnswerContent,6,false,true,PageDto.Id,null,null,null), token);

        }
        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;
        }
    }
}