import {LitElement, html} from './lit-all.min.js';
import * as tfrpc from '/static/tfrpc.js';

class TfCollectionsAppElement extends LitElement {
	static get properties() {
		return {
			ids: {type: Array},
			whoami: {type: String},
			wiki: {type: String},
			wiki_doc: {type: Object},
		};
	}

	constructor() {
		super();
		this.ids = [];
		this.load();
	}

	async load() {
		this.ids = await tfrpc.rpc.getIdentities();
		this.whoami = await tfrpc.rpc.localStorageGet('collections_whoami');
	}

	async on_whoami_changed(event) {
		let new_id = event.srcElement.selected;
		await tfrpc.rpc.localStorageSet('collections_whoami', new_id);
		this.whoami = new_id;
	}

	async on_wiki_publish(event) {
		let blob_id = event.detail.id;
		let message = {
			type: 'wiki-doc',
			key: this.wiki_doc.id,
			parent: this.wiki_doc.parent,
			blob: blob_id,
		};
		print(message);
		await tfrpc.rpc.appendMessage(this.whoami, message);
		return this.load();
	}

	render() {
		let self = this;
		return html`
			<h1 style="color: #fff">Hello!</h1>
			<tf-id-picker .ids=${this.ids} selected=${this.whoami} @change=${this.on_whoami_changed}></tf-id-picker>
			<tf-collections whoami=${this.whoami} kind="wiki" @selected=${(event) => self.wiki = event.detail.id}></tf-collections>
			${this.wiki ? html`<tf-collections whoami=${this.whoami} type="wiki-doc" parent=${this.wiki} @selected=${(event) => self.wiki_doc = event.detail.value}></tf-collections>` : undefined}
			${this.wiki_doc ? html`<tf-wiki-doc whoami=${this.whoami} .value=${this.wiki_doc} @publish=${this.on_wiki_publish}></tf-wiki-doc>` : undefined}
		`;
	}
}

customElements.define('tf-collections-app', TfCollectionsAppElement);