import { CustomHTMLElement } from "./lib/custom_html_element.mjs"
import { API } from 'api'

export class N2PageStorage extends CustomHTMLElement {
	static {// {{{
		this.tmpl = document.createElement('template')
		this.tmpl.innerHTML = `
			<style>
				.table {
					display: grid;
					grid-template-columns: min-content min-content;
					grid-gap: 4px 16px;
					align-items: center;
					white-space: nowrap;
				}

				.error {
					background-color: #ff2a2a;
					color: #fff;
					padding: 4px 8px;
					border-radius: 4px;
				}

				h2 {
					margin-top: 24px;
					margin-bottom: 8px;
				}

				.el-btn-clear-all {
					margin-top: 16px;
				}
			</style>

			<h1>Local storage</h1>

			<h2>Notes</h2>
			<div class="table">
				<div>Local notes</div>
				<div data-el="count-nodes"></div>

				<div>History notes</div>
				<div data-el="count-history-nodes"></div>

				<div>Notes to send</div>
				<div data-el="count-queued-nodes"></div>
			</div>

			<h2>Files</h2>
			<div class="table">
				<div>Files on server</div>
				<div data-el="count-files-on-server"></div>

				<div>Files on device</div>
				<div data-el="count-files-on-device"></div>

				<div>Files to send</div>
				<div data-el="count-queued-files"></div>
			</div>

			<h2>Clear storage</h2>
			<div>Remove all data from this device (not server) and logout the session.</div>
			<div>This ensures that no notes or files is left on the browser.</div>
			<button data-el="btn-clear-all">Clear and logout</button>
		`
	}// }}}
	constructor() {// {{{
		super(true)

		.elBtnClearAll.addEventListener('click', ()=>this.clearAll())

		window._mbus.subscribe('SHOW_PAGE', event => {
			if (event.detail.data?.page == 'storage')
				this.render()
		})
	}// }}}
	async render() {// {{{
		API.query('GET', '/file/count')
			.then(res => {
				this.elCountFilesOnServer.innerText = res.Count
			})
			.catch(err => {
				this.elCountFilesOnServer.classList.add('error')
				console.error(err)
				this.elCountFilesOnServer.innerText = err.message
			})


		this.elCountNodes.innerText = await globalThis.nodeStore.nodeCount()
		this.elCountQueuedNodes.innerText = await globalThis.nodeStore.sendQueue.count()
		this.elCountHistoryNodes.innerText = await globalThis.nodeStore.nodesHistory.count()
		this.elCountQueuedFiles.innerText = await globalThis.nodeStore.filesMetadata.countToUpload()

		this.elCountFilesOnDevice.innerText = await globalThis.nodeStore.filesMetadata.count()
	}// }}}
	clearAll() {// {{{
		if (!confirm('Do you want to remove ALL data from this device and logout?'))
			return

		globalThis.nodeStore.deleteAll()
	}// }}}
}
customElements.define('n2-pagestorage', N2PageStorage)
