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

class TfTabNewsElement extends LitElement {
	static get properties() {
		return {
			whoami: {type: String},
			users: {type: Object},
			hash: {type: String},
			unread: {type: Array},
			following: {type: Array},
			drafts: {type: Object},
			expanded: {type: Object},
			loading: {type: Boolean},
		};
	}

	static styles = styles;

	constructor() {
		super();
		let self = this;
		this.whoami = null;
		this.users = {};
		this.hash = '#';
		this.unread = [];
		this.following = [];
		this.cache = {};
		this.drafts = {};
		this.expanded = {};
		tfrpc.rpc.localStorageGet('drafts').then(function (d) {
			self.drafts = JSON.parse(d || '{}');
		});
	}

	connectedCallback() {
		super.connectedCallback();
		document.body.addEventListener('keypress', this.on_keypress.bind(this));
	}

	disconnectedCallback() {
		super.disconnectedCallback();
		document.body.removeEventListener('keypress', this.on_keypress.bind(this));
	}

	show_more() {
		let unread = this.unread;
		let news = this.shadowRoot?.getElementById('news');
		if (news) {
			console.log('injecting messages', news.messages);
			news.add_messages(
				Object.values(Object.fromEntries(this.unread.map((x) => [x.id, x])))
			);
			this.dispatchEvent(new CustomEvent('refresh'));
		}
	}

	new_messages_text() {
		if (!this.unread?.length) {
			return 'No new messages.';
		}
		let counts = {};
		for (let message of this.unread) {
			let type = 'private';
			try {
				type = JSON.parse(message.content).type || type;
			} catch {}
			counts[type] = (counts[type] || 0) + 1;
		}
		return (
			'↻ Show New: ' +
			Object.keys(counts)
				.sort()
				.map((x) => counts[x].toString() + ' ' + x + 's')
				.join(', ')
		);
	}

	draft(event) {
		let id = event.detail.id || '';
		let previous = this.drafts[id];
		if (event.detail.draft !== undefined) {
			this.drafts[id] = event.detail.draft;
		} else {
			delete this.drafts[id];
		}
		this.drafts = Object.assign({}, this.drafts);
		tfrpc.rpc.localStorageSet('drafts', JSON.stringify(this.drafts));
	}

	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);
		}
	}

	on_keypress(event) {
		if (event.target === document.body && event.key == '.') {
			this.show_more();
		}
	}

	render() {
		let profile = this.hash.startsWith('#@')
			? html`<tf-profile
					id=${this.hash.substring(1)}
					whoami=${this.whoami}
					.users=${this.users}
				></tf-profile>`
			: undefined;
		let edit_profile;
		if (
			!this.loading &&
			this.users[this.whoami]?.name === undefined &&
			this.hash.substring(1) != this.whoami
		) {
			edit_profile = html` <div
				class="w3-panel w3-padding w3-round w3-card-4 w3-theme-l3"
			>
				ℹ️ Follow your identity link ☝️ above to edit your profile and set your
				name.
			</div>`;
		}
		return html`
			<p class="w3-bar">
				<button
					class="w3-bar-item w3-button w3-theme-d1"
					@click=${this.show_more}
				>
					${this.new_messages_text()}
				</button>
			</p>
			<div class="w3-bar">
				Welcome, <tf-user id=${this.whoami} .users=${this.users}></tf-user>!
				${edit_profile}
			</div>
			<div>
				<tf-compose
					id="tf-compose"
					whoami=${this.whoami}
					.users=${this.users}
					.drafts=${this.drafts}
					@tf-draft=${this.draft}
				></tf-compose>
			</div>
			${profile}
			<tf-tab-news-feed
				id="news"
				whoami=${this.whoami}
				.users=${this.users}
				.following=${this.following}
				hash=${this.hash}
				.drafts=${this.drafts}
				.expanded=${this.expanded}
				@tf-draft=${this.draft}
				@tf-expand=${this.on_expand}
			></tf-tab-news-feed>
		`;
	}
}

customElements.define('tf-tab-news', TfTabNewsElement);