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;
				}
			</style>

			<h1>Local storage</h1>

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

				<div>Queued to sync</div>
				<div data-el="count-queued-nodes"></div>

				<div>History nodes</div>
				<div data-el="count-history-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>
		`
	}
	constructor() {
		super(true)

		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()
	}
}
customElements.define('n2-pagestorage', N2PageStorage)
