// 采用Promise构造的同步返回
let gResolveId = 0;
const gResolveMap = new Map();

function postMessageToFlutter(data) {
  // 检查是否在macOS的WKWebView环境中
  if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.webview) {
      window.webkit.messageHandlers.webview.postMessage(data);
  }
  // 检查是否在Windows的WebView2环境中
  else if (window.chrome && window.chrome.webview) {
      window.chrome.webview.postMessage(data);
  }
  // 不支持的环境
  else {
      console.error("Unsupported platform or message handler not found.");
  }
}

// 前端发送消息给dart
window.postMessage = (data) => {
    return new Promise((resolve) => {
      gResolveId++;
      gResolveMap.set(gResolveId, resolve);
      let package = {id: gResolveId, data: data};
      // window?.chrome?.webview?.postMessage(package);
      postMessageToFlutter(package);
    });
};

// dart处理完后调用(用于同步)
window._recvPackage = (package) => {
  //console.log(`_recvPackage:` + JSON.stringify(package));
  gResolveMap.get(package.id)?.call(this, package.data);
  gResolveMap.delete(package.id);
};

// 前端接收消息函数(覆盖该函数)
window.recvMessage = (data) => {
  //console.log(`recvMessage:` + JSON.stringify(data));
};

// 接收dart主动通知
window?.chrome?.webview?.addEventListener("message", (data) => {
  // 默认前端接收数据函数
  //console.log(`recvMessage:` + JSON.stringify(data.data));
  window?.recvMessage?.call(this, data.data);
});

function receiveMessageFromFlutter(data) {
  //console.log(`receiveMessageFromFlutter:` + JSON.stringify(data));
  window?.recvMessage?.call(this, data);
}

// 页面加载完毕向客户端发送ready消息
document.addEventListener("DOMContentLoaded", () => {
  //console.log("DOMContentLoaded");
	window.postMessage({type: 0x0006, ratio: window.devicePixelRatio.toString()});
});

// 屏蔽F12
document.addEventListener("keydown", (e) => {
  if(e.key == "F12") {
    e.preventDefault(); 
	}
});