import 'package:application/service/api.dart';
import 'package:application/service/map_watch.dart';
import 'package:application/logger.dart';
import 'package:get/get.dart';
import '../home_controller.dart';
export 'package:application/service/map_watch.dart';


extension ActiveInfoExt2 on ActiveInfo{
  Future<void> update(ToActionInfo info) async {
    final newUserList = <UserInfo>[];

    for (final nUser in info.userList) {
      late UserInfo user;
      final oUser = getUserById(nUser.userId);
      if (oUser != null) {
        user = oUser;
        await user.update(nUser);

      }else{
        user = await newUserInfo(nUser);
      }

      newUserList.add(user);
    }
    userList = newUserList;
  }
}


class FieldControlController extends GetxController{
  HomeController get _home => Get.find();
  MapWatchService? get mapWatch => MapWatchService.instance;
  final activeList = <ActiveInfo>[].obs;

  @override
  void onInit() {
    super.onInit();
    workFlushData();
  }

  Future<void> workFlushData()async{
    while(!isClosed){
      try{
        await flushData();
      }catch(e){
        error(e);
      }
      await 1.seconds.delay();
    }
  }

  ActiveInfo? getActiveById(int id){
    for (final one in activeList){
      if(one.id==id){
        return one;
      }
    }
    return null;
  }

  Future<void> flushData()async{
    final r = await ApiService.to.stub.toUserDetailQueryV2(ToUserDetailQueryRequestV2(
        mapId: mapWatch?.id.toInt()));

    final newList = <ActiveInfo>[];

    for(final one in r.list){
      late ActiveInfo info;
      final old = getActiveById(one.actId);
      if(old != null){
        info = old;
        await info.update(one);
      }else{
        info = await one.into();
      }
      newList.add(info);
    }

    activeList.value = newList;
  }
}