import 'package:flutter/cupertino.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import 'package:keyboard/resource/string.gen.dart';
import 'package:keyboard/utils/string_format_util.dart';
import 'package:keyboard/utils/toast_util.dart';

import '../../../../../utils/intimacy_analyze_config_helper.dart';
import 'custom_direction_edit_view.dart';

/// 自定义预测方向的编辑弹窗的Controller
@injectable
class CustomDirectionEditController extends BaseController {
  /// 亲密度分析的帮助类
  final IntimacyAnalyzeConfigHelper intimacyAnalyzeConfigHelper;

  /// TextField操作控制器
  final TextEditingController editingController = TextEditingController();

  /// 输入框焦点
  final FocusNode inputFocusNode = FocusNode();

  CustomDirectionEditController(this.intimacyAnalyzeConfigHelper);

  @override
  void onClose() {
    inputFocusNode.dispose();
    editingController.dispose();
    super.onClose();
  }

  /// 获取自定义预测方向，最大自定义字符数
  int getMaxCustomDirectionWords() {
    return intimacyAnalyzeConfigHelper.getMaxCustomDirectionWords();
  }

  /// 保存
  void doOnSave(OnSaveCallback onSaveCallback) {
    // 必须输入内容
    String userInput = editingController.text.trim();

    if (userInput.isEmpty) {
      ToastUtil.show(StringName.inputCommonHint);
      return;
    }

    // 限制最小保存字符
    int minCustomDirectionWords =
        intimacyAnalyzeConfigHelper.getMinCustomDirectionWords();
    if (userInput.length < minCustomDirectionWords) {
      String msg = StringFormatUtil.formatStr(
        StringName.inputMininputTip,
        minCustomDirectionWords.toString(),
      );
      ToastUtil.show(msg);
      return;
    }

    onSaveCallback(userInput);

    // 清空输入框
    editingController.text = "";
  }

  /// 关闭
  void doClose(OnCloseCallback onCloseCallback) {
    // 清空输入框
    editingController.text = "";
    onCloseCallback();
  }

  /// 让输入框获取焦点
  void doRequestInputFocus() {
    Future.delayed(const Duration(milliseconds: 300), () {
      inputFocusNode.requestFocus();
    });
  }

  /// 让输入框失去焦点
  void doInputUnFocus() {
    inputFocusNode.unfocus();
  }
}
