const FILENAME = '/CLodopfuncs.js';

function loadByScript(url, protocol = 'http://', name = FILENAME) {
  if (!url.startsWith(protocol)) url = `${protocol}${url}`;
  if (!url.endsWith(name)) url = `${url}${name}`;
  if (window['getCLodop']) return Promise.resolve();
  return new Promise((resolve, reject) => {
    const el = document.createElement('script');
    el.src = url;
    el.addEventListener('load', resolve);
    el.addEventListener('error', reject);
    document.head.appendChild(el);
  });
}

function loadByWebSocket(url, protocol = 'ws://', name = FILENAME) {
  if (!url.startsWith(protocol)) url = `${protocol}${url}`;
  if (!url.endsWith(name)) url = `${url}${name}`;
  if (window['getCLodop']) return Promise.resolve();
  return new Promise((resolve, reject) => {
    const ws = new WebSocket(url);
    ws.addEventListener('open', () => { setTimeout(reject, 200); });
    ws.addEventListener('error', reject);
    ws.addEventListener('message', (e) => {
      if (!window['getCLodop']) eval(e.data);
      resolve();
    });
  });
}

export default function load(options) {
  const {ws, http, https, licenses} = Object.assign({
    ws: (process.env.VUE_APP_C_LODOP_WS || 'localhost:8000|localhost:18000').split('|'),
    http: (process.env.VUE_APP_C_LODOP_HTTP || 'localhost:8000|localhost:18000').split('|'),
    https: (process.env.VUE_APP_C_LODOP_HTTPS || 'localhost.lodop.net:8443').split('|'),
    licenses: (process.env.VUE_APP_C_LODOP_LICENSES || '').split('|'),
  }, options);

  const disable = location.protocol === 'https:';

  return Promise.any(ws.map((url) => loadByWebSocket(url)))
    .catch(() => Promise.any(https.map(url => loadByScript(url, 'https://'))))
    .catch(e => {
      if (disable) throw e;
      return Promise.any(http.map(url => loadByScript(url)));
    })
    .then(() => {
      const instance = window['getCLodop']();
      for (const license of licenses) {
        const value = license.split('_');
        instance['SET_LICENSES'](...value);
      }
      return instance;
    });
}
