import * as React from "react";

import "../style/search.scss";

class Search extends React.Component {

	private searchInput = React.createRef<HTMLInputElement>()

	constructor(props) {
		super(props);
	}

	handleQuery(query: string) {
		this.search(query);
	}

	search(query: string){
		const url = new URL("https://duckduckgo.com/");
		const param = new URLSearchParams();
		param.append("q",query);
		url.search = param.toString();
		window.location.href = url.toString();
	}

	onKeyDown(event: React.KeyboardEvent) {
		if (event.key === 'Enter') {
			this.handleQuery(this.searchInput.current.value);
		}
	}

	render(): JSX.Element {
		return <div className="search-component" >
			<input type="text" 
				autoFocus
				onKeyDown={(e)=>this.onKeyDown(e)}
				ref={this.searchInput}
				/>
		</div>;
	}

}

export default Search;
