import 'dart:typed_data';
import 'package:web_socket_channel/web_socket_channel.dart';

import 'package:wukongimfluttersdk/common/logs.dart';
import 'package:wukongimfluttersdk/manager/my_wk_socket_base.dart';

class MyWkSocketChannel implements MyWkSocketBase {
  WebSocketChannel? _socket; // 将 _socket 声明为可空类型
  bool _isListening = false;

  static MyWkSocketChannel? _instance;
  MyWkSocketChannel._internal(this._socket);

  factory MyWkSocketChannel.newSocket(WebSocketChannel webSocketChannel) {
    _instance ??= MyWkSocketChannel._internal(webSocketChannel);
    return _instance!;
  }

  @override
  void close() {
    _isListening = false;
    _instance = null;
    try {
      _socket?.sink.close();
    } finally {
      _socket = null; // 现在可以将 _socket 设置为 null
    }
  }

  @override
  void listen(
      {required Function(Uint8List data) onData,
      required Function() onOpen,
      required Function() error}) {
    if (!_isListening && _socket != null) {
      _socket!.stream.listen(
        (message) {
          onData(message);
        },
        onDone: () {
          Logs.debug('socket onDone');
          close(); // 关闭和重置 Socket 连接
          error();
        },
        onError: (error) {
          Logs.debug('socket断开了${error.toString()}');
        },
      );
      _isListening = true;
    }
  }

  @override
  send(Uint8List data) {
    try {
      if (_socket != null) {
        _socket?.sink.add(data); // 使用安全调用操作符
      }
    } catch (e) {
      Logs.debug('发送消息错误$e');
    }
  }

  @override
  bool isConnect() {
    if (_socket != null && _socket?.closeCode == null) {
      return true;
    } else {
      return false;
    }
  }
}
