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

class TfTabMentionsElement extends LitElement {
	static get properties() {
		return {
			whoami: {type: String},
			users: {type: Object},
			following: {type: Array},
			expanded: {type: Object},
			messages: {type: Array},
		};
	}

	static styles = styles;

	constructor() {
		super();
		let self = this;
		this.whoami = null;
		this.users = {};
		this.following = [];
		this.expanded = {};
		this.messages = [];
	}

	async load() {
		console.log('Loading...', this.whoami);
		let results = await tfrpc.rpc.query(`
				SELECT messages.*
				FROM messages_fts(?)
				JOIN messages ON messages.rowid = messages_fts.rowid
				JOIN json_each(?) AS following ON messages.author = following.value
				WHERE messages.author != ?
				ORDER BY timestamp DESC limit 20
			`,
			['"' + this.whoami.replace('"', '""') + '"', JSON.stringify(this.following), this.whoami]);
		console.log('Done.');
		this.messages = results;
	}

	on_expand(event) {
		if (event.detail.expanded) {
			let expand = {};
			expand[event.detail.id] = true;
			this.expanded = Object.assign({}, this.expanded, expand);
		} else {
			delete this.expanded[event.detail.id];
			this.expanded = Object.assign({}, this.expanded);
		}
	}

	render() {
		let self = this;
		if (!this.loading) {
			this.loading = true;
			this.load();
		}
		return html`
			<tf-news id="news" whoami=${this.whoami} .messages=${this.messages} .users=${this.users} .expanded=${this.expanded} @tf-expand=${this.on_expand}></tf-news>
		`;
	}
}
customElements.define('tf-tab-mentions', TfTabMentionsElement);