import type { ExtensionConfig } from '@vtj/core';
import type { EngineOptions } from '@vtj/designer';

import * as Vue from 'vue';

import * as core from '@vtj/core';
import * as designer from '@vtj/designer';
import * as VtjIcons from '@vtj/icons';
import * as renderer from '@vtj/renderer';
import * as VtjUI from '@vtj/ui';
import * as VtjUtils from '@vtj/utils';
import * as ElementPlus from 'element-plus';

export type ExtensionOptions = ExtensionConfig;
export type ExtensionFactory = (
  config: ExtensionConfig
) => Partial<EngineOptions> | void;

export interface ExtensionOutput {
  options: Partial<EngineOptions>;
  adapters: Record<string, any>;
}

export class Extension {
  private __adapters__: Record<string, any> = {};
  private __BASE_PATH__: string = '/';
  private library: string = '';
  private params: any[] = [];
  private urls: string[] = [];
  constructor(private options: ExtensionOptions) {
    const __VTJ_PRO__ = {
      ...core,
      ...designer,
      ...renderer
    };

    (window as any).Vue = Vue;
    (window as any).__VTJ_PRO__ = __VTJ_PRO__;
    (window as any).VtjUtils = VtjUtils;
    (window as any).VtjIcons = VtjIcons;
    (window as any).VtjUI = VtjUI;
    (window as any).ElementPlus = ElementPlus;
    const {
      urls = [],
      library,
      params = [],
      __BASE_PATH__ = '/',
      __adapters__ = {}
    } = options || {};
    this.urls = urls;
    this.library = library;
    this.params = params;
    this.__BASE_PATH__ = __BASE_PATH__;
    this.__adapters__ = __adapters__;
  }
  async load(): Promise<ExtensionOutput> {
    let options: Partial<EngineOptions> = {};
    if (this.library) {
      const base = this.__BASE_PATH__;
      const css = this.urls
        .filter((n) => renderer.isCSSUrl(n))
        .map((n) => `${base}${n}`);
      const scripts: string[] = this.urls
        .filter((n) => renderer.isJSUrl(n))
        .map((n) => `${base}${n}`);
      renderer.loadCssUrl(css);
      if (scripts.length > 0) {
        const output = await renderer
          .loadScriptUrl(scripts, this.library)
          .catch(() => null);
        options =
          output && typeof output === 'function'
            ? output.call(output, this.options, this.params)
            : output || {};
      }
    }
    return {
      options,
      adapters: this.__adapters__
    };
  }
}
