'use strict';

var show_log = false;
var ws_worker_id = null;
var worker_name = this.name;

var build = worker_name.split(':')[1].split(' ')[2];
var domain = worker_name.split(':')[1].split(' ')[3];

if (build === 'undefined') {
  build = '';
}

const get_url = function (domain, method, path) {
  return `https://${domain}/${method}${
    path ? '/' + path : ''
    // return `https://${subdomain ? subdomain + "." : ""}${domain}${path ? "/" + path : ""
  }`;
};

const runtime_path = get_url(domain, 'dist', 'runtime/');

const get_resource_filename = function (build, filename) {
  if (build) {
    return filename.replace(/(\.\w+)$/, `.${build}$1`);
  }
  return filename;
};

if (worker_name.includes('Debug:')) {
  importScripts(get_resource_filename(build, runtime_path + 'js/xuda-worker-bundle.js'));
  importScripts(runtime_path + 'node_modules/lodash/lodash.js');
  importScripts(runtime_path + 'node_modules/klona/full/index.min.js');
  importScripts(runtime_path + 'node_modules/json5/dist/index.js');
} else {
  if (worker_name.includes('Dev:')) {
    let files = ['xuda_common.js', 'xuda_GLB.js', 'xuda_datasource.js', 'xuda_utils.js', 'xuda_events.js', 'xuda_expression.js'];
    files.forEach((file) => {
      importScripts(file);
    });

    importScripts('../vendor/lodash.min.js');
    importScripts('..vendor/klona-2.0.6.min.js');
    importScripts('../vendor/json5.min.js');
  } else {
    importScripts(get_resource_filename(build, runtime_path + 'js/xuda-worker-bundle.min.js'));
    importScripts(runtime_path + 'node_modules/lodash/lodash.js');
    importScripts(runtime_path + 'node_modules/klona/full/index.min.js');
    importScripts(runtime_path + 'node_modules/json5/dist/index.js');
  }
}
if (!worker_name.includes('Slim ')) {
  importScripts(runtime_path + 'node_modules/pouchdb/dist/pouchdb.min.js');
  importScripts(runtime_path + 'node_modules/pouchdb/dist/pouchdb.find.min.js');
}

glb.IS_WORKER = true;
SESSION_ID = 1000;
console.log('===========================================');
console.log(' Worker started...' + new Date().getTime());
console.log('===========================================');

const worker_post_message = function (data) {
  if (!data.process_pid) {
    delete data.process_pid;
  }

  if (!data.service) {
    delete data.service;
  }
  try {
    postMessage(data);
  } catch (error) {
    debugger;
  }
};

self.addEventListener(
  'message',
  async function (e) {
    ws_worker_id = e.data.worker_id;
    if (!ws_worker_id) debugger;

    const _data = JSON.parse(e.data.data);

    if (e.data.service === 'init') {
      worker_garbage_collector(_data.session_id);
    }
    const ret = await eval(func.utils.ws_worker.functions[e.data.service])(_data, e.data.promise_queue_id);
    if (!e.data.service || e.data.service === 'init' || e.data.service === 'datasource_create') {
      return;
    }
    worker_post_message({
      fx_to_execute: 'worker_response',
      worker_id: ws_worker_id,
      session_id: SESSION_ID,
      promise_queue_id: e.data.promise_queue_id,
      service: e.data.service,
      params: ret,
    });
  },
  false,
);

worker_post_message({
  worker_id: ws_worker_id,
  service: 'worker_ready',
});

const worker_garbage_collector = function (SESSION_ID) {
  setInterval(() => {
    for (const [dsP, _ds] of Object.entries(SESSION_OBJ[SESSION_ID].DS_GLB)) {
      if (_ds.is_worker && _ds.stat === 'idle' && Date.now() - _ds.stat_ts > 60000 && _ds.tree_obj.menuType !== 'component' && _ds.tree_obj.menuType !== 'globals') {
        func.datasource.del(SESSION_ID, dsP);
      }
    }
  }, 10000);
};
