// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

// declare global: tern, server
/**
 * Tern 服务 Worker 端（后台线程处理 Tern 分析任务）
 * 功能：在 Web Worker 中运行 Tern 引擎，接收主线程指令（初始化、文件操作、分析请求），
 *       处理后返回结果，避免阻塞主线程
 */
var server;
/**
 * 监听主线程消息（处理各类指令）
 * @param {Event} e - 消息事件对象（e.data 为指令数据）
 */
this.onmessage = function(e) {
  var data = e.data;
  switch (data.type) {
  case "init": return startServer(data.defs, data.plugins, data.scripts);
  case "add": return server.addFile(data.name, data.text);
  case "del": return server.delFile(data.name);
  case "req": return server.request(data.body, function(err, reqData) {
    postMessage({id: data.id, body: reqData, err: err && String(err)});
  });
  case "getFile":
    var c = pending[data.id];
    delete pending[data.id];
    return c(data.err, data.text);
  default: throw new Error("Unknown message type: " + data.type);
  }
};

var nextId = 0, pending = {};
function getFile(file, c) {
  postMessage({type: "getFile", name: file, id: ++nextId});
  pending[nextId] = c;
}

function startServer(defs, plugins, scripts) {
  if (scripts) importScripts.apply(null, scripts);

  server = new tern.Server({
    getFile: getFile,
    async: true,
    defs: defs,
    plugins: plugins
  });
}

var console = {
  log: function(v) { postMessage({type: "debug", message: v}); }
};
