/**
 * Here we display the entire parsed, finsemble configuration.
 */
import React, { Component } from "react"; // eslint-disable-line
import LoggerStore from "../../../stores/LoggerStore";
import ConfigSearchBox from "./ConfigSearchBox";
import Highlighter from "../../highlighter/Highlighter";

interface IProps {}
interface IState {
	config: any[];
	showSearchBox: boolean;
	searchBoxText: string;
}

class ConfigViewer extends Component<IProps, IState> {
	constructor(props: IProps) {
		super(props);
		this.state = {
			config: [],
			showSearchBox: LoggerStore.getShowSearchBox(),
			searchBoxText: LoggerStore.getSearchBoxString(),
		};
		this.setShowSearchBox = this.setShowSearchBox.bind(this);
		this.onSearchUpdate = this.onSearchUpdate.bind(this);
		this.scrollToActiveLine = this.scrollToActiveLine.bind(this);
	}

	setShowSearchBox() {
		this.setState({
			showSearchBox: LoggerStore.getShowSearchBox(),
		});
	}

	onSearchUpdate() {
		this.setState({
			searchBoxText: LoggerStore.getSearchBoxString(),
		});
	}

	componentWillUnmount() {
		LoggerStore.removeListener("showSearchBoxChange", this.setShowSearchBox);
		LoggerStore.removeListener("searchBoxTextChange", this.onSearchUpdate);
		LoggerStore.removeListener("activeConfigSearchMatch", this.scrollToActiveLine);
	}

	componentDidMount() {
		LoggerStore.addListener("searchBoxTextChange", this.onSearchUpdate);
		LoggerStore.addListener("showSearchBoxChange", this.setShowSearchBox);
		LoggerStore.addListener("activeConfigSearchMatch", this.scrollToActiveLine);
		LoggerStore.getFullConfig((cfg) => {
			this.setState({ config: cfg });
		});
	}

	scrollToActiveLine() {
		const activeLine = LoggerStore.getActiveConfigSearchMatch();
		const activeLineDOMReference = this.refs[`line${activeLine}`] as HTMLPreElement;
		if (activeLineDOMReference) {
			activeLineDOMReference.scrollIntoView();
		}
	}

	render() {
		const cfg = this.state.config;
		return (
			<div className="config-viewer">
				<div className="config">
					{cfg.map((line, i) => {
						const str = `line${i}`;
						return (
							<pre ref={str} key={i}>
								<Highlighter ind={i} str={line} searchBoxText={this.state.searchBoxText} />
							</pre>
						);
					})}
				</div>
				<ConfigSearchBox show={this.state.showSearchBox} />
			</div>
		);
	}
}

export default ConfigViewer;
