import { ModuleEvents, ModuleStatus, ModuleConfig, ModuleResources, ModuleElements, ModuleManifest, Application } from '../types'
class ModuleProptey {
  public id: string
  public param: object = {}
  public application: Application
  public events: ModuleEvents = {
    transformStart: () => undefined,
    transformEnd: () => undefined,
    start: () => undefined,
    load: () => undefined,
    loadError: () => undefined,
    preload: () => undefined,
    destroy: () => undefined
  }
  public createTime = Date.now()
  public transient = false
  public shadowView: HTMLElement | HTMLPortalElement | HTMLIFrameElement | null = null
  public shadowViewType: 'iframe' | 'portal' | null = null
  public mutationObserver!: MutationObserver
  public status: ModuleStatus = {
    init: false,
    preload: false,
    prefetch: false,
    prerender: false
  }

  public config: ModuleConfig = {
    title: '',
    rel: 'module',
    level: 0,
    source: {},
    prerender: [],
    apply: ['smart-setTimeout', 'link-in-new-window', ['tap-highlight', 'tap-highlight data-appeared']],
    free: true,
    background: 'auto'
  }

  public resources: ModuleResources = {
    script: [],
    image: [],
    worker: [],
    video: [],
    audio: [],
    font: [],
    style: []
  }

  public elements: ModuleElements = {
    container: document.body
  }

  constructor (id: string, model: ModuleManifest, application: Application) {
    this.id = id
    this.param = {}
    this.application = application

    const { config, resources, events } = this.setDefaultConfig(model)
    Object.assign(this.config, config)
    Object.assign(this.resources, resources)
    Object.assign(this.events, events)
  }

  public setDefaultConfig (manifest: ModuleManifest) {
    if (manifest.config?.rel === 'frameworks') {
      // Module.framework = model
    }
    if (manifest.config?.portal) {
      if (!manifest.config.free) {
        console.error('Module.config[free & portal] conflit!')
      }
    }
    if (isNaN(manifest.config?.level)) {
      manifest.config.level = 0
    }
    if (manifest.config.level > 10000) {
      console.error('Module.confi.level <= 9999!')
    }

    return manifest
  }
}

export {
  ModuleProptey
}
