
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';

enum  OpenTokSDKState{ LOGGED_OUT, LOGGED_IN, WAIT, ON_CALL, ERROR }
final _platformMethodChannel = const MethodChannel('OpenTok-Platform-Bridge');

class OpenTokPlatformBridge{


  OpenTokSDKState _sdkState = OpenTokSDKState.LOGGED_OUT;
  bool _publishAudio = true;
  bool _publishVideo = true;

  final void Function(OpenTokSDKState) onStateChange;

  OpenTokPlatformBridge.init({@required String sessionID, @required String token, @required String apiKey, this.onStateChange}){
    _initSession({'apiKey':apiKey, 'sessionId':sessionID, 'token':token, });
    _platformMethodChannel.setMethodCallHandler(incomingMethodHadler);
  }
  
  Future<dynamic> incomingMethodHadler(MethodCall methodCall) async {
    switch (methodCall.method) {
      case 'updateState':
        {
          var arguments = 'OpenTokSDKState.${methodCall.arguments}';
          _sdkState = OpenTokSDKState.values.firstWhere((v) {
            return v.toString() == arguments;
          });
          onStateChange(_sdkState);
        }
        break;
      default:
        throw MissingPluginException('notImplemented');
    }
  }


  Future<void> _initSession(Map<String,String> openTokCredentials) async {
    await requestPermissions();
    try {
      await _platformMethodChannel.invokeMethod('initSession', openTokCredentials);
    } on PlatformException catch (e) {
      print(e);
    }
  }

  Future<void> makeCall() async {
    try {
      await requestPermissions();

      await _platformMethodChannel.invokeMethod('makeCall');
    } on PlatformException catch (e) {
      print(e);
    }
  }

  Future<void> requestPermissions() async {
    await [Permission.microphone, Permission.camera].request();
  }

  Future<void> swapCamera() async {
    try {
      await _platformMethodChannel.invokeMethod('swapCamera');
    } on PlatformException catch (e) {}
  }

  Future<void> toggleAudio() async {
    try {
      await _platformMethodChannel.invokeMethod('toggleAudio');
    } on PlatformException catch (e) {}
  }

  Future<void> toggleVideo() async {
    try {
      await _platformMethodChannel.invokeMethod('toggleVideo');
    } on PlatformException catch (e) {}
  }

  Future<void> hangupCall() async {
    try {
      await _platformMethodChannel.invokeMethod('hangupCall');
    } on PlatformException catch (e) {}
  }
}
