import 'dart:async';

import 'package:common_pub/ui/map_view/view_map_cp.dart';
import 'package:track_common/model.dart';
import 'package:track_common/service/map_watch.dart';

class FieldControlController extends GetxController {
  final _mapWatch = Get.find<MapWatchService>();

  @override
  void onInit() {
    final map = _mapWatch.instance;
    if (map != null) {
      eventList.clear();
      eventList.bindStream(map.eventList.stream);
    }

    _subActive = eventList.listen((p0) {
      final user = focusUser;
      if (user != null) {
        viewCpController.setCPList(user.cpList);
      }
    });
    super.onInit();
  }

  @override
  void onClose() {
    super.onClose();
    _subActive?.cancel();
  }

  final viewCpController = ViewMapCPController();
  StreamSubscription<List<EventOnMap>>? _subActive;
  MapWatch? get mapWatch => _mapWatch.instance;
  final eventList = <EventOnMap>[].obs;
  final Rx<int?> focusUserId = Rx(null);

  PlayerOnMap? findFocusUser(List<EventOnMap> list) {
    if (focusUserId.value == null) {
      return null;
    }

    for (final act in list) {
      for (final user in act.userList) {
        if (user.id == focusUserId.value) {
          return user;
        }
      }
    }
    return null;
  }

  PlayerOnMap? get focusUser {
    return findFocusUser(eventList);
  }
}
