import { reactive } from 'vue';
import { Widget, WidgetModify, VueComponent } from './types';
import { merge, isString } from '../utils';
import { buildInWidgets } from '../components';

/**
 * 布局骨架类
 */
export class Skeleton {
  public readonly widgets: Widget[];
  // 在WidgetRenderer记录组件的实例
  public widgetInstances: Record<string, VueComponent> = {};

  public regions: Record<string, VueComponent> = {};

  constructor(widgets: Widget[]) {
    this.widgets = reactive<Widget[]>(widgets);
  }

  load(widgets: Widget[]) {
    widgets.forEach((item: Widget) => {
      this.add(item);
    });
  }

  get(name: string) {
    return this.widgets.find((n: Widget) => n.name === name);
  }

  set(name: string, modify: WidgetModify) {
    const widget = this.get(name);
    if (widget) {
      merge(widget, modify);
    }
  }

  add(widget: Widget) {
    const exist = !!this.get(widget.name);
    if (exist) {
      this.set(widget.name, widget);
    } else {
      this.widgets.push(widget);
    }
  }

  remove(name: string) {
    const index = this.widgets.findIndex((n: Widget) => n.name === name);
    if (index >= 0) {
      const widget = this.widgets[index];
      widget.disabled = true;
      this.widgets.splice(index, 1);
    }
  }

  getComponent(type: string | any) {
    if (!type) return buildInWidgets.Empty;
    if (isString(type)) {
      return buildInWidgets[type] || buildInWidgets.Empty;
    }
    return type;
  }
}
