import 'dart:async';
import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:vnote_device_plugin/events/event_center.dart';
import 'package:vnote_device_plugin/utils/logger.dart';

import 'vnote_device_plugin_platform_interface.dart';

/// An implementation of [VnoteDevicePluginPlatform] that uses method channels.
class MethodChannelVnoteDevicePlugin extends VnoteDevicePluginPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('vnote_device_plugin');

  final eventChannel = const EventChannel("vnote_device_plugin_event");

  StreamSubscription<dynamic>? _eventChannelSubcription;

  @override
  Future<String?> getPlatformVersion() async {
    final version =
        await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  @override
  Future<void> callAction(String action, Map<String, dynamic> data) async {
    data["ACTION"] = action;
    await methodChannel.invokeMethod(
      "callAction",
      {
        "request": jsonEncode(data),
      },
    );
  }

  @override
  Future<void> init([bool isDebug = false]) async {
    if (isDebug) {
      await LogUtil.init();
      await LogUtil.setEnable(true);
    }
    _eventChannelSubcription ??=
        eventChannel.receiveBroadcastStream().listen(_onEventReceived);
    return methodChannel.invokeMethod(
      "init",
      {
        "isDebug": isDebug,
      },
    );
  }

  @override
  Future<void> setLogEnable(bool enable) async {
    if (!enable) {
      LogUtil.write("Disable Logger!");
    }

    await LogUtil.setEnable(enable);
    await methodChannel.invokeMethod(
      "setLogEnable",
      {
        "enable": enable,
      },
    );

    if (enable) {
      LogUtil.write("Enable Logger!");
    }
  }

  @override
  bool get isLogEnable => LogUtil.enable;

  void _onEventReceived(dynamic event) {
    DeviceEventCenter.instance.emit(event);
  }
}
