import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:keyboard/data/bean/member_info.dart';
import 'package:keyboard/data/repository/account_repository.dart';
import 'package:keyboard/data/repository/characters_repository.dart';
import 'package:keyboard/data/repository/keyboard_repository.dart';
import '../utils/mmkv_util.dart';

class KeyboardMethodHandler {
  final KeyboardRepository keyboardRepository;
  final CharactersRepository charactersRepository;
  final AccountRepository accountRepository;

  // 用处存储选中的键盘id
  static const String keyboardSelect = 'keyboard_select';

  bool get isLogin => accountRepository.isLogin.value;
  bool get isMember => accountRepository.isMember.value;

  KeyboardMethodHandler(
    this.keyboardRepository,
    this.charactersRepository,
    this.accountRepository,
  );

  Future<dynamic> handleMethodCall(MethodCall call) async {
    switch (call.method) {
      case 'getKeyboardList':
        return _handleGetKeyboardList(call);
      case 'selectedKeyboard':
        return _handleSelectedKeyboard(call);
      case 'getCharacterList':
        return _handleGetCharacterList(call);
      case 'getCurrentKeyboardId':
        return _handleGetCurrentKeyboardId(call);
      case 'getPrologueList':
        return _handleGetPrologueList(call);
      case 'isLogin':
        return isLogin;
      case 'isMember':
        return isMember;


      default:
        throw MissingPluginException('Not implemented: ${call.method}');
    }
  }

  Future<String> _handleGetKeyboardList(MethodCall call) async {
    String? type = call.arguments?['type'] as String?;
    final keyboardList = await keyboardRepository.getKeyboardList(type: type);

    final selectKeyboardId = KVUtil.getString(keyboardSelect, null);

    if (selectKeyboardId != null) {
      for (var element in keyboardList.keyboardInfos) {
        if (element.id == selectKeyboardId) {
          element.isSelect = true;
        }
      }
    }
    return jsonEncode(keyboardList.toJson());
  }

  Future<String> _handleSelectedKeyboard(MethodCall call) async {
    final String keyboardId = call.arguments['keyboardId'];
    KVUtil.putString(keyboardSelect, keyboardId);
    return "{}";
  }

  Future<String> _handleGetCurrentKeyboardId(MethodCall call) async {
    String? keyboardId = KVUtil.getString(keyboardSelect, null);
    if (keyboardId == null) {
      return "{}";
    }
    return jsonEncode({"keyboardId": keyboardId});
  }

  Future<String> _handleGetCharacterList(MethodCall call) async {
    final String keyboardId = call.arguments['keyboardId'];
    final characterList = await keyboardRepository.getKeyboardCharacterList(
      keyboardId: keyboardId,
    );
    return jsonEncode(characterList.toJson());
  }

  //   获取开场白列表
  Future<String> _handleGetPrologueList(MethodCall call) async {
    final prologueList = await keyboardRepository.getPrologueList();
    return jsonEncode(prologueList.toJson());
  }
}
