import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/device_status.dart';

class DeviceNotifier extends Notifier<DeviceStatus> {
  Timer? _timer;

  @override
  DeviceStatus build() {
    _startSimulation();
    ref.onDispose(() {
      _timer?.cancel();
    });
    return const DeviceStatus(connected: true, battery: 82.0);
  }

  void _startSimulation() {
    _timer = Timer.periodic(const Duration(seconds: 5), (timer) {
      if (state.battery > 0) {
        state = state.copyWith(
          battery: state.connected ? state.battery - 0.05 : state.battery,
          signalStrength: state.connected ? (85 + (timer.tick % 10)).toInt() : 0,
        );
      }
    });
  }

  void toggleConnection() {
    state = state.copyWith(connected: !state.connected);
  }
}

final deviceProvider = NotifierProvider<DeviceNotifier, DeviceStatus>(DeviceNotifier.new);
