using Mapster;

namespace DeviceManagement.ViewModels.Dialog;

internal partial class EditDeviceViewModel(DeviceCollection deviceCollection) : ObservableObject, IDialogAware
{
    public DialogCloseListener RequestClose { get; set; }
    [ObservableProperty]
    private DeviceInfo_VM? _TempDevice;

    [ObservableProperty]
    private string? _Title;

    public bool CanCloseDialog()
    {
        return true;
    }

    public void OnDialogClosed()
    {

    }

    public void OnDialogOpened(IDialogParameters parameters)
    {
        this.Title = "设备编辑";
        if (!parameters.TryGetValue<DeviceInfo_VM>("Device", out DeviceInfo_VM? device) || device is null)
        {
            this.RequestClose.Invoke();
            return;
        }
        this.TempDevice = new();
        device.Adapt(this.TempDevice);
    }

    [RelayCommand]
    private void SaveDevice()
    {
        if (this.TempDevice is null||this.TempDevice.Guid is null)
        {
            MessageBox.Show("Error");
            return;
        }

        if (!deviceCollection.DeviceList.TryGetValue(this.TempDevice.Guid.Value, out DeviceInfo_VM? device) || device is null)
        {
            MessageBox.Show("Error");
            return;
        }

        this.TempDevice.Adapt(device);
        MessageBox.Show("设备信息修改成功！", "设备信息", MessageBoxButton.OK, MessageBoxImage.Information);
        this.RequestClose.Invoke();

    }

    [RelayCommand]
    private void Close()
    {
        this.RequestClose.Invoke();
    }
}
