export class TreeContents extends HTMLElement {
		get contents() {
				return JSON.parse(this.getAttribute('contents'))
		}
		get name() {
				return this.getAttribute('name')
		}
		get type() {
				return this.getAttribute('type')
		}
		get url() {
				return this.getAttribute('url')
		}
		get info() {
				return this.getAttribute('info')
		}
		connectedCallback() {
				this.render()
		}
		render() {
				const $header = document.createElement('tree-header')
				const $type = document.createElement('tree-type')
				$type.innerText = this.type

				const $name = document.createElement('tree-name')
				const $nameLink = document.createElement('a')
				$nameLink.innerText = this.name
				$nameLink.href = this.url
				$name.append($nameLink)

				const $info = document.createElement('tree-info')
				$info.innerText = this.info

				$header.append($type)
				$header.append($name)
				this.info && $header.append($info)

				this.append($header)

				this.contents && this.renderSubContent()
		}
		renderSubContent() {
				this.contents.forEach(content => {
						const {name, type, info} = content
						const $contents = document.createElement('tree-contents')
						$contents.setAttribute('url', `${this.url}/${encodeURI(name)}`)
						$contents.setAttribute('name', name)
						type && $contents.setAttribute('type', type)
						info && $contents.setAttribute('info', info)
						if (content.contents) {
								$contents.setAttribute('contents', JSON.stringify(content.contents))
						}
						this.append($contents)
				})
		}
}

export default class TreeWeb extends HTMLElement {
		constructor() {
				super()
				this.data = {}
				this.baseUrl = ''
				this.report = null
				this.directory = null
		}
		async connectedCallback() {
				const res = await fetch('./index.json')
				this.data = await res.json()
				this.report = this.data.filter(item => item.type === 'report')[0]
				this.directory = this.data.filter(item => item.type === 'directory')[0]
				// href
				const href = window.location.href
				this.baseUrl = href.endsWith('/') ? href.slice(0, href.length -1) : href
				this.render()
		}
		render() {
				const { name, type, info, contents } = this.directory

				const $contents = document.createElement('tree-contents')
				$contents.setAttribute('contents', JSON.stringify(contents))
				$contents.setAttribute('url', this.baseUrl)
				name && $contents.setAttribute('name', name)
				type && $contents.setAttribute('type', type)
				info && $contents.setAttribute('info', info)

				this.append($contents)
		}
}

if (!customElements.get('tree-web')) {
		customElements.define('tree-web', TreeWeb)
}
if (!customElements.get('tree-contents')) {
		customElements.define('tree-contents', TreeContents)
}
