import 'dart:async';

import 'package:flutter/services.dart';

class SpeechPlugin {
  static const MethodChannel _channel =
      const MethodChannel('speech_plugin');

  static final SpeechPlugin _instance = SpeechPlugin();

  StreamController _onEvaluatorChange;
  Stream<Map> get evaluator => _onEvaluatorChange.stream;
  static int evaluatorType = 0;
  static SpeechSdk speechSdk = SpeechSdk.IFly;

  static SpeechPlugin get instance => _instance;

  static Future<String> get platformVersion async {
    final String version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  Future<void> initSdk() {
    return _channel.invokeMethod("initSpeechSdk");
  }

  void updateEvaluatorType({int plevType}) {
    SpeechPlugin.evaluatorType = plevType; // 1为开启全维度，0为关闭
  }

  void updateEvaluatorSdkType({SpeechSdk sdkType}) {
    SpeechPlugin.speechSdk = sdkType; // 1为开启chivox，0为讯飞
  }

 Future<Map> evaluatorByAudio(String pathEvaluatorDecode, int index, String videoId, String recordPath, String en, {int evaluatorType}) {
    return _channel.invokeMethod("evaluatorByAudio", {
      "pathEvaluatorDecode": pathEvaluatorDecode,
      "index": index,
      "videoId": videoId,
      "recordPath": recordPath,
      "en": en,
      "evaluatorType": evaluatorType ?? SpeechPlugin.evaluatorType,
      "sdkType": speechSdk.index,
    });
 }

 Future<Map> evaluatorByMp4(String pathEvaluatorDecode, int index, String videoId, String recordPath, String en, {int evaluatorType}) {
   return _channel.invokeMethod("evaluatorByMp4", {
     "pathEvaluatorDecode": pathEvaluatorDecode,
     "index": index,
     "videoId": videoId,
     "recordPath": recordPath,
     "en": en,
     "evaluatorType": evaluatorType ?? SpeechPlugin.evaluatorType,
     "sdkType": speechSdk.index,
   });
 }

  /// 初始化listener 进入页面时调用
  void initListener() {
    _onEvaluatorChange = new StreamController<Map>.broadcast();
    _channel.setMethodCallHandler(_onMethodCallHandler);
  }

  /// 原生返回数据回调方法
  /// 录音进度
  Future _onMethodCallHandler(MethodCall call) {
    switch (call.method) {
      case "evaluatorResult":
        _onEvaluatorChange.add(call.arguments);
        break;
    }
    return null;
  }

  /// 关闭stream
  void closeStream() {
    _channel.setMethodCallHandler(null);
    _onEvaluatorChange.close();
  }

}

enum SpeechSdk {
  IFly, Chivox, SmartOral // 0 讯飞 1 词声 2 腾讯
}
