'use strict';

const { Controller } = require('ee-core');
const Log = require('ee-core/log');
const CoreWindow = require('ee-core/electron/window');
const WebSocket = require('ws'); // 引入原生 ws 库
let socket = null;
class SocketController extends Controller {
  constructor(ctx) {
    super(ctx);
  }

  /**
   * Connect to WebSocket server
   */
  async connect() {
    if(socket)  return;

    return new Promise(async (resolve,reject) => {
      socket = new WebSocket('ws://10.56.42.176:7074/ws');

      const win = CoreWindow.getMainWindow()
      // 监听连接成功事件
      socket.on('open', () => {
        console.log('socket open')
        resolve(true);
      });

      // 监听消息事件
      socket.on('message', (data) => {
        try {
          let this_data = JSON.parse(data.toString());
          if(this_data.msg_type){
            let channel = 'controller.socket.message_'+this_data.msg_type;
            win.webContents.send(channel, this_data);
            //   win.webContents.send('controller.socket.message', data.toString());

          }
        }catch (e){
          console.log(e)
        }
      });

      // 监听连接关闭事件
      socket.on('close', () => {
        console.log('socket close');

      });

      // 监听错误事件
      socket.on('error', (err) => {
        console.log('socket error');
        console.log(error);
        reject(true);

      });


    })

  }

  /**
   * 发送 ping 消息
   */
  sendPing() {
    const message = JSON.stringify({ data: 'node', type: 'ping' });
    this.sendMessage(message);
  }

  /**
   * 发送消息到服务器
   * @param {string} message - JSON 字符串
   */
  sendMessage(message) {
    // 检查连接状态
    console.log(message);
    console.log(typeof socket);
    if (socket?.readyState === WebSocket.OPEN) {
      socket.send(message); // 使用 send() 发送
    } else {
    }
  }

  /**
   * 断开连接
   */
  disconnect() {
    if (socket) {
      socket.close(); // 使用 close() 方法
      socket = null;
    }
  }
}

SocketController.toString = () => '[class SocketController]';
module.exports = SocketController;
