import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/utils/keyboard.dart';
import 'package:flyinsono/managers/interfaces/group.dart';
import 'package:get/get.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'index.dart';

class GroupListController extends FControllerBase
    with EnterPressListenOnControllerMixin {
  final searchController = TextEditingController();

  GroupListController();
  final groupManager = Get.find<IGroupManager>();
  final state = GroupListState();

  int getGroupTotalMemberNum(UserGroupDTO? group) {
    if (group == null) return 0;
    int deviceNum = 0;
    int userNum = 0;
    if (group.deviceCodes != null) {
      deviceNum = group.deviceCodes!.length;
    }
    if (group.userCodes != null) {
      userNum = group.userCodes!.length;
    }
    return deviceNum + userNum;
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    _initData();
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  Future<void> _initData() async {
    state.groups = await groupManager.getGroups();
    if (state.groups.isNotEmpty) {
      state.selectedGroupCode = state.groups.first.code!;
    }
  }

  Future<void> searchGrooups() async {
    state.groups = await groupManager.getGroups(keyword: searchController.text);
  }

  @override
  void onEnterPressed() {
    searchGrooups();
  }
}
