import {LitElement, html} from './lit-all.min.js';
import * as tfrpc from '/static/tfrpc.js';
import {styles, generate_theme} from './tf-styles.js';
class TfTabConnectionsElement extends LitElement {
	static get properties() {
		return {
			broadcasts: {type: Array},
			identities: {type: Array},
			my_identities: {type: Array},
			connections: {type: Array},
			stored_connections: {type: Array},
			users: {type: Object},
			server_identity: {type: String},
			connect_attempt: {type: Object},
			connect_message: {type: String},
			connect_success: {type: Boolean},
			peer_exchange: {type: Boolean},
		};
	}
	static styles = styles;
	static k_broadcast_emojis = {
		discovery: '🏓',
		room: '🚪',
		peer_exchange: '🕸',
	};
	constructor() {
		super();
		let self = this;
		this.broadcasts = [];
		this.identities = [];
		this.my_identities = [];
		this.connections = [];
		this.stored_connections = [];
		this.users = {};
		tfrpc.rpc.getIdentities().then(function (identities) {
			self.my_identities = identities || [];
		});
		tfrpc.rpc.getAllIdentities().then(function (identities) {
			self.identities = identities || [];
		});
		tfrpc.rpc.getStoredConnections().then(function (connections) {
			self.stored_connections = connections || [];
		});
		tfrpc.rpc.getServerIdentity().then(function (identity) {
			self.server_identity = identity;
		});
		this.check_peer_exchange();
	}
	async check_peer_exchange() {
		if (await tfrpc.rpc.isAdministrator()) {
			this.peer_exchange = await tfrpc.rpc.globalSettingsGet('peer_exchange');
		} else {
			this.peer_exchange = undefined;
		}
	}
	async enable_peer_exchange() {
		await tfrpc.rpc.globalSettingsSet('peer_exchange', true);
		await this.check_peer_exchange();
	}
	render_connection_summary(connection) {
		if (connection.address && connection.port) {
			return html`
				${connection.address}:${connection.port} 
			
`;
		} else if (connection.tunnel) {
			return html`room peer
`;
		} else {
			return JSON.stringify(connection);
		}
	}
	render_room_peers(connection) {
		let self = this;
		let peers = this.broadcasts.filter((x) => x.tunnel?.id == connection);
		if (peers.length) {
			let connections = this.connections.map((x) => x.id);
			return html`${peers
				.filter((x) => connections.indexOf(x.pubkey) == -1)
				.map((x) => html`${self.render_room_peer(x)}`)}`;
		}
	}
	async _tunnel(portal, target) {
		return tfrpc.rpc.createTunnel(portal, target);
	}
	render_room_peer(connection) {
		let self = this;
		return html`
			
				 self._tunnel(connection.tunnel.id, connection.pubkey)}
				>
					Connect
				 
				 
		`;
	}
	render_message(connection) {
		return html` (this.connect_attempt = undefined)}
		>
			
${this.connect_message}
		
					
						${name} ${value} / ${max} (${Math.round((100.0 * value) / max)}%)
					
				 
			`;
		}
	}
	render_broadcast(connection) {
		let self = this;
		return html`
			
				
					 self.connect(connection)}
					>
						Connect
					 
					
						${TfTabConnectionsElement.k_broadcast_emojis[connection.origin]}
						
				 
				${this.render_message(connection)}
			 
		`;
	}
	async forget_stored_connection(connection) {
		await tfrpc.rpc.forgetStoredConnection(connection);
		this.stored_connections = (await tfrpc.rpc.getStoredConnections()) || [];
	}
	render_connection(connection) {
		let requests = Object.values(
			connection.requests.reduce(function (accumulator, value) {
				let key = `${value.name}:${Math.sign(value.request_number)}`;
				if (!accumulator[key]) {
					accumulator[key] = Object.assign({count: 0}, value);
				}
				accumulator[key].count++;
				return accumulator;
			}, {})
		);
		return html`
			${connection.connected
				? html`
						 tfrpc.rpc.closeConnection(connection.id)}
						>
							Close
						 
					`
				: undefined}
			${connection.flags.one_shot ? '🔃' : undefined}
			
				${requests.map(
					(x) => html`
						${x.request_number > 0 ? '🟩' : '🟥'} ${x.name}
							 1 ? undefined : 'display: none'}
								>${x.count}  
					`
				)}
			
			
				${this.connections
					.filter((x) => x.tunnel === this.connections.indexOf(connection))
					.map((x) => html`${this.render_connection(x)} `)}
				${this.render_room_peers(connection.id)}
			 
			
				${connection.destroy_reason}
			 
		`;
	}
	connect(address) {
		let self = this;
		self.connect_attempt = address;
		self.connect_message = undefined;
		self.connect_success = false;
		tfrpc.rpc
			.connect(address)
			.then(function () {
				if (self.connect_attempt == address) {
					self.connect_message = 'Connected.';
					self.connect_success = true;
				}
			})
			.catch(function (error) {
				if (self.connect_attempt == address) {
					self.connect_message = 'Error: ' + error;
					self.connect_success = false;
				}
			});
	}
	toggle_accordian(id) {
		let element = this.renderRoot.getElementById(id);
		element.classList.toggle('w3-hide');
	}
	valid_connections() {
		return this.connections.filter((x) => x.tunnel === undefined);
	}
	valid_broadcasts() {
		return this.broadcasts
			.filter((x) => x.address)
			.filter((x) => this.connections.map((c) => c.id).indexOf(x.pubkey) == -1);
	}
	render() {
		let self = this;
		return html`
			
			
				
					
						Looking for connections? Enabling this option will include publicly
						advertised rooms and pubs among the list of discovered connections
						to help you replicate.
					
					
						🔍🌐 Use publicly advertised peers
					 
				 
				New Connection 
				
				${this.render_message(this.renderRoot.getElementById('code')?.value)}
				
						self.connect(self.renderRoot.getElementById('code')?.value)}
				>
					Connect
				 
				
				
					${this.valid_connections().map(
						(x) => html` ${this.render_connection(x)}  `
					)}
				 
				
				
					${this.valid_broadcasts().map((x) => self.render_broadcast(x))}
				 
				
				
					${this.stored_connections.map(
						(x) => html`
							
								
									 self.forget_stored_connection(x)}
									>
										Forget
									 
									 this.connect(x)}
									>
										Connect
									 
									
										${x.address}:${x.port} 
										
											Last connection:
												${new Date(x.last_success * 1000)} 
										
									 
								 
								${this.render_message(x)}
							 
						`
					)}
				 
				
				
					${this.identities.map(
						(x) =>
							html`
								${x == this.server_identity
									? html`
											🖥 local server
										
`
									: undefined}
								${this.my_identities.indexOf(x) != -1
									? html`
											😎 you
										
`
									: undefined}
								
`
					)}
				
 
		`;
	}
}
customElements.define('tf-tab-connections', TfTabConnectionsElement);