import { CustomHTMLElement } from './lib/custom_html_element.mjs'

export class N2PageHistory extends CustomHTMLElement {
	static PAGESIZE = 10

	static {
		this.tmpl = document.createElement('template')
		this.tmpl.innerHTML = `
			<style>
				n2-pagehistory {
					margin-top: 32px;

					.layout {
					}
				}
			</style>

			<div class="layout">
				<img data-el="back-image" src="/images/${_VERSION}/icon_back.svg" class="colorize">
				<div data-el="back-text">Back to node</div>

				<img src="/images/${_VERSION}/icon_history.svg" class="colorize">
				<h1 data-el="node-name"></h1>

				<div data-el="nodes"></div>


				<div class="pagination">
					<div data-el="prev">&lt;</div>
					<div data-el="page"></div>
					<div data-el="next">&gt;</div>
				</div>
			</div>
		`
	}

	constructor() {
		super()

		// Connect back icon and text to give the user a way back to the node.
		this.elBackImage.addEventListener('click', () => _mbus.dispatch('SHOW_PAGE', { page: 'node' }))
		this.elBackText.addEventListener('click', () => _mbus.dispatch('SHOW_PAGE', { page: 'node' }))
		this.elPrev.addEventListener('click', ()=>this.prevPage())
		this.elNext.addEventListener('click', ()=>this.nextPage())

		_mbus.subscribe('NODE_UI_OPEN', async (event) => {
			await this.useNode(event.detail.data)
			this.render()
		})
	}

	async useNode(node) {
		this.node = node
		this.page = 1

		this.nodesTotal = await nodeStore.nodesHistory.count(this.node.UUID)
		this.pages = Math.ceil(this.nodesTotal / N2PageHistory.PAGESIZE)
	}


	prevPage() {
		if (this.page == 1)
			return
		this.page--
		this.render()
	}

	nextPage() {
		if (this.page >= this.pages)
			return
		this.page++
		this.render()
	}

	async render() {
		this.elNodeName.innerText = this.node.get('Name')
		this.elPage.innerText = `${this.page} / ${this.pages}`

		this.elNodes.innerHTML = ''
		let nodes = await nodeStore.nodesHistory.retrievePage(this.node.UUID, N2PageHistory.PAGESIZE, this.page)
		let i = 0
		for (const n of nodes) {
			i++
			const div = document.createElement('div')
			div.innerHTML = `
				<div>${N2PageHistory.PAGESIZE * (this.page - 1) + i}</div>
				<div>${n.get('Updated').replace('T', ' ')}</div>
			`
			div.classList.add('history-node')
			this.elNodes.append(div)
		}
	}
}
customElements.define('n2-pagehistory', N2PageHistory)
