namespace DeviceScanner.ViewModels;

public partial class ScannerViewModel : ObservableObject
{
    public ScannerViewModel(DeviceCollection deviceCollection, IDialogService dialogService)
    {
        this._DialogService = dialogService;
        this.ScanningDevices = [];
        this.EnableShader = false;
        this.ShaderVisibility = Visibility.Collapsed;
    }

    private readonly IDialogService _DialogService;


    [ObservableProperty]
    private ObservableDictionary<string, DeviceInfo_VM> _ScanningDevices;

    [ObservableProperty]
    private bool _EnableShader;

    [ObservableProperty]
    private Visibility _ShaderVisibility;


    [RelayCommand]
    private void CreateDevice(DeviceInfo_VM deviceInfo)
    {
        IDialogParameters paras = new DialogParameters
        {
            { "Device", deviceInfo }
        };
        this._DialogService.Show("CreateDevice", paras, null);
    }

    [RelayCommand]
    private void Scan(string para)
    {
        switch (para)
        {
            case "Start":
                this.ShaderVisibility = Visibility.Visible;
                this.EnableShader = true;
                if (this._FakeDataTimer is not null)
                    return;
                this.ScanningDevices.Clear();
                this._FakeDataTimer = new(FakeDataTimerCallback, null, 5000, 5000);
                break;
            case "Stop":
                this.ShaderVisibility = Visibility.Collapsed;
                this.EnableShader = false;
                this._FakeDataTimer?.Dispose();
                this._FakeDataTimer = null;
                break;
            case "Clear":
                if (this._FakeDataTimer is not null)
                    return;
                this.ScanningDevices.Clear();
                break;
            default:
                break;
        }
    }

    private Timer? _FakeDataTimer;

    private void FakeDataTimerCallback(object? state)
    {
        Random rnd = new();

        DeviceModel model = (DeviceModel)rnd.Next(0, 2);

        int i = rnd.Next(0, 4);
        object subModel = model switch
        {
            DeviceModel.JetKepler => (KeplerSubModel)i,
            DeviceModel.Proxima => (ProximaSubModel)i,
            _ => string.Empty
        };

        DeviceInfo_VM device = new()
        {
            DeviceModel = model,
            DeviceSubModel = subModel.ToString(),
            SoftwareVersion = $"1.0.0.{rnd.Next(1, 20)}",
            IP = $"192.168.250.{rnd.Next(1, 255)}",
            Port = 50003,
        };
        Application.Current.Dispatcher?.Invoke(() =>
        {
            this.ScanningDevices.TryAdd(device.IP, device);
        });
    }
}
