import { ModuleProptey } from './proptey'
import { ModuleConfig, ModuleManifest, Application } from '../types'

class ModuleState extends ModuleProptey {
  constructor (id: string, model: ModuleManifest, application: Application) {
    super(id, model, application)
  }

  get sameOrigin (): boolean {
    if (!this.uri) return true
    const link = document.createElement('a')
    link.href = this.uri
    const isSameOrigin = link.host === location.host
    return isSameOrigin
  }

  get level (): number {
    const level = this.config.level || (this.application.activeModule?.config.level || 1) + 1
    const baseLevel = this.config.free ? 20000 : 10000
    return baseLevel + level
  }

  get rel (): 'system' | 'frameworks' | 'module' {
    if (this.id === 'system') return 'system'
    if (this.id === 'frameworks') return 'frameworks'
    return this.config.rel || 'module'
  }

  get uri (): string {
    return this.config?.source?.src || ''
  }

  get viewType (): 'portal' | 'iframe' | 'shadow' {
    if (this.rel !== 'module') return 'shadow'
    if (!this.config?.portal || !this.uri) return 'iframe'
    if (!this.shadowViewType) {
      const type = ('HTMLPortalElement' in window) && this.sameOrigin ? 'portal' : 'iframe'
      this.shadowViewType = type
    }
    return this.shadowViewType
  }
}

export {
  ModuleState
}
