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

class TfAppsElement extends LitElement {
	static get properties() {
		return {
			user: {type: String},
			whoami: {type: String},
			my_apps: {type: Array},
			shared_apps: {type: Array},
			core_apps: {type: Array},
			index: {type: String},
		};
	}

	constructor() {
		super();
		let self = this;
		tfrpc.register(function set() {
			self.set(...arguments);
		});
		this.load();
	}

	load() {
		let self = this;
		tfrpc.rpc.getActiveIdentity().then((x) => (self.whoami = x));
		tfrpc.rpc.getUser().then((x) => (self.user = x));
		this.my_apps = undefined;
		this.shared_apps = undefined;
		this.core_apps = undefined;
		this.my_apps = tfrpc.rpc.get_my_apps();
		this.shared_apps = tfrpc.rpc.get_shared_apps();
		this.core_apps = tfrpc.rpc.get_core_apps();
		tfrpc.rpc
			.isAdministrator()
			.then(function (x) {
				return x ? tfrpc.rpc.globalSettingsGet('index') : undefined;
			})
			.then(function (x) {
				self.index = x;
			});
	}

	set(key, value) {
		if (key == 'identity') {
			this.load();
		}
	}

	connectedCallback() {
		super.connectedCallback();
		this._load = this.load.bind(this);
		document.body.addEventListener('app-publish', this._load);
	}

	disconnectedCallback() {
		document.body.removeEventListener('app-publish', this._load);
		super.disconnectedCallback();
	}

	render() {
		return html`
			<link type="text/css" rel="stylesheet" href="w3.css" />
			<header class="w3-container">
				<h1>Welcome to Tilde Friends</h1>
			</header>
			<div class="w3-container">
				<tf-app-group
					id="my_apps"
					name="Your Apps"
					user=${this.user}
					whoami=${this.whoami}
					index=${this.index}
					.apps=${this.my_apps}
				></tf-app-group>
				<tf-app-group
					id="core_apps"
					name="Core Apps"
					user=${this.user}
					whoami=${this.whoami}
					index=${this.index}
					.apps=${this.core_apps}
				></tf-app-group>
				<tf-app-group
					id="shared_apps"
					name="Shared Apps"
					user=${this.user}
					whoami=${this.whoami}
					index=${this.index}
					.apps=${this.shared_apps}
				></tf-app-group>
			</div>
		`;
	}
}

customElements.define('tf-apps', TfAppsElement);
