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

class BookEditElement extends LitElement {
	static get properties() {
		return {
			book: {type: Object},
			search_results: {type: Object},
		};
	}

	add_author() {
		if (!this.book) {
			this.book = {};
		}
		if (!this.book.authors) {
			this.book.authors = [];
		}
		this.book.authors.push('');
		this.book = Object.assign({}, this.book);
	}

	edit_field(event) {
		if (!this.book) {
			this.book = {};
		}
		this.book[event.srcElement.id] = event.srcElement.value;
		this.book = Object.assign({}, this.book);
	}

	author_keyup(event) {
		if (
			event.srcElement.value === '' &&
			(event.key == 'Backspace' ||
				event.key == 'Escape' ||
				event.key == 'Delete')
		) {
			this.book.authors.splice(event.srcElement.dataset.index);
			this.book = Object.assign({}, this.book);
		}
	}

	search_keypress(event) {
		if (event.key == 'Enter') {
			this.search();
		}
	}

	async search() {
		this.search_results = {searching: true};
		let query = this.renderRoot.getElementById('search_text').value;
		let response = await fetch(
			`https://openlibrary.org/search.json?q=${encodeURIComponent(query)}&fields=title,description,key,author_name,editions,cover_i`
		);
		let json = await response.json();
		this.search_results = json;
	}

	render_shelf(shelf) {
		return html` <div class="w3-tag w3-padding w3-gray">${shelf}</div> `;
	}

	async import_book(book) {
		if (!this.book) {
			this.book = {};
		}
		if (!this.book.authors) {
			this.book.authors = [];
		}
		this.book.title = book.title;
		this.book.description = book.description;
		this.book.authors = book.author_name;
		let url = `https://covers.openlibrary.org/b/id/${book.cover_i}-M.jpg`;
		let response = await fetch(url);
		let blob = await response.blob();
		let bytes = Array.from(await blob.bytes());
		this.book.image = {
			link: await tfrpc.rpc.store_blob(bytes),
			size: bytes.length,
			name: `image:${book.cover_i}-M.jpg`,
			type: 'image/jpeg',
		};
		this.search_results = undefined;
		this.book = Object.assign({}, this.book);
	}

	async submit() {
		let whoami = await tfrpc.rpc.getActiveIdentity();
		let message = {
			type: this.book.id ? 'bookclubUpdate' : 'bookclub',
			updates: this.book.id,
			title: this.book.title,
			description: this.book.description,
			authors: this.book.authors,
			image: this.book.image,
		};
		console.log(message);
		await tfrpc.rpc.appendMessage(whoami, message);
	}

	render_search_results() {
		if (this.search_results) {
			if (this.search_results.searching) {
				return html`<p>Searching...</p>`;
			}
			return map(
				this.search_results.docs,
				(x) => html`
					<div class="w3-card w3-padding">
						<img
							src=${`https://covers.openlibrary.org/b/id/${x.cover_i}-M.jpg`}
						/>
						<h1>${x.title}</h1>
						<h2>${x.author_name?.join(', ')}</h2>
						<p>${x.description}</p>
						<button
							class="w3-button w3-gray"
							@click=${() => this.import_book(x)}
						>
							Import Book
						</button>
					</div>
				`
			);
		}
	}

	render() {
		return html`
			<link rel="stylesheet" href="w3.css"></link>
			<div class="w3-margin">
				<a class="w3-button w3-gray" target="_top" href="#">Back</a>
				<div class="w3-row w3-margin-top w3-margin-bottom" style="box-sizing: border-box">
					<input id="search_text" type="text" class="w3-row-item w3-input w3-threequarter w3-light-gray" @keypress=${this.search_keypress}></input>
					<button class="w3-row-item w3-button w3-gray w3-quarter" @click=${this.search}>Search</button>
				</div>
				${this.render_search_results()}

				<div>
					${this.book?.id ? html`<div><i>Updating ${this.book.id}.</i></div>` : undefined}
					<label for="title">Book Title</label>
					<input id="title" class="w3-input" placeholder="Title" value=${this.book?.title} @change=${this.edit_field}></input>
					<div>
						<label for="authors">Authors</label>
						<ul>
							${this.book?.authors?.map(
								(x, index) => html`
								<li><input class="w3-input" value=${x} data-index=${index} @keyup=${this.author_keyup}></input></li>
							`
							)}
						</ul>
						<button class="w3-button w3-gray" @click=${this.add_author}>Add Author</button>
					</div
					<label for="description">Book Description</label>
					<textarea id="description" class="w3-input" placeholder="Description" @change=${this.edit_field}>${this.book?.description}</textarea>
					<div class="w3-container">
						${
							this.book?.image
								? html` <img
										src="/${typeof this.book?.image === 'string'
											? this.book?.image
											: this.book?.image?.link}/view"
										class="w3-left w3-margin-right w3-margin-bottom"
										style="max-height: 2in; max-width: 2in"
									/>`
								: undefined
						}
					</div>
					<button class="w3-button w3-gray" @click=${this.submit}>Submit</button>
				</div>
			</div>`;
	}
}

customElements.define('bc-book-edit', BookEditElement);
