<?php
if( !isset($_SERVER['CONTENT-TYPE']) || !( $_SERVER['CONTENT_TYPE'] == "application/json" )) {
	require_once dirname(__FILE__).'/how-to.php';
} else {
	log_request( $_SERVER );
	
	/**
	 * No need to instantiate Suggest for empty requests
	 */
	if( empty( $_GET ) ) {
		print_r( json_encode( array() ) );
		die();
	}
	
	require_once dirname(__FILE__).'/spelling-suggester/suggest.php';
	$s = new Suggest( dirname(__FILE__).'/words/big.txt' );

	$suggestions = array();
	foreach( $_GET as $word => $value ) {
		$suggestions[ $word ] = $s( $word );
	}

	switch( $_SERVER['CONTENT-TYPE'] ) {
		default:
		case 'application/json': {
			header('Content-type: application/json');
			print_r( json_encode( $suggestions ) );
		}
	}
}

function log_request( $request ) {
	file_put_contents( dirname(__FILE__).'/logs/requests.log', serialize( $request )."\n", FILE_APPEND );
}
