/**
 * Collar at the top of the page housing import/export, localhost:9090 link, and a link to the process monitor.
 */
import React from "react";
import LoggerStore from "../stores/LoggerStore";
import LoggerButton from "./LoggerButton";
import { System } from "../../../../common/system";

import LauncherClient from "../../../../clients/launcherClient";

LauncherClient.initialize();

interface IProps {
	activeView: string;
	showProcessMonitor: boolean;
}
interface IState {
	logCount: {
		master: number;
		display: number;
	};
	clientListVisible: boolean;
}

// high-level affects on central logger.  Buttons to invoke ClearData, Export, Import, and Save Settings.
export default class TopCollar extends React.PureComponent<IProps, IState> {
	constructor(props: IProps) {
		super(props);
		this.state = {
			logCount: LoggerStore.getLogCounts(),
			clientListVisible: LoggerStore.getClientListVisible(),
		};

		this.getNewLogCounts = this.getNewLogCounts.bind(this);
		this.updateClientListVisible = this.updateClientListVisible.bind(this);
	}

	componentDidMount() {
		LoggerStore.addListener("loggerNewMessages", this.getNewLogCounts);
		LoggerStore.addListener("clientListVisibleChange", this.updateClientListVisible);
	}

	componentWillUnmount() {
		LoggerStore.removeListener("loggerNewMessages", this.getNewLogCounts);
		LoggerStore.removeListener("clientListVisibleChange", this.updateClientListVisible);
	}

	clearData() {
		LoggerStore.clearData();
	}

	saveToFile() {
		LoggerStore.saveToFile();
	}

	fileMode() {
		LoggerStore.fileMode();
	}

	persist() {
		LoggerStore.persistState.persist();
	}

	getNewLogCounts() {
		this.setState({
			logCount: LoggerStore.getLogCounts(),
		});
	}

	toggleClientList() {
		LoggerStore.toggleClientListVisible();
	}

	updateClientListVisible() {
		this.setState({
			clientListVisible: LoggerStore.getClientListVisible(),
		});
	}

	spawnProcessMonitor() {
		LauncherClient.spawn("Process Monitor", {});
	}

	spawnLocalhost9090() {
		System.openUrlWithBrowser("http://localhost:9090");
	}

	render() {
		return (
			<div className="logger-row top-collar row-shadow">
				{this.props.activeView === "logger" && (
					<LoggerButton title="CTRL+ALT+C" onClick={this.toggleClientList}>
						{this.state.clientListVisible ? "Hide " : "Show "}
						Left Panel
					</LoggerButton>
				)}
				{this.props.showProcessMonitor && (
					<LoggerButton onClick={this.spawnProcessMonitor}>Process Monitor</LoggerButton>
				)}
				<LoggerButton onClick={this.spawnLocalhost9090}>localhost:9090</LoggerButton>
				<div className="pull-right">
					<div className="fsbl-logger-buttons">
						<LoggerButton onClick={this.saveToFile}>Export Log</LoggerButton>
						<LoggerButton onClick={this.fileMode}>Import Log</LoggerButton>
					</div>
				</div>
			</div>
		);
	}
}
