<?php

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

Class OpenstatesApiClient {
	private $client = null;
	private $apiKey = null;
	const API_URL = 'https://openstates.org/api/v1/';

	public function __construct($key) {
		$this->apiKey = $key;
		$this->client = new Client([
			'base_uri' => self::API_URL,
			'headers' => [
				'X-API-KEY' => $key,
				'Content-Type' => 'application/json',
				'Accept' => 'application/json'
			]
		]);
	}

	public function geoSearch($args){
		$url = 'legislators/geo/?lat=' . $args['lat'] . '&long=' . $args['long'];
		return $this->request($url);
	}

	public function stateSearch($stateCode){
		$url = 'legislators/?state=' . strtolower($stateCode);
		return $this->request($url);
	}

	private function request($endpoint) {
		try {
			// TODO: do not include api key in transient, instead use a shortened hash
			$transient_key = self::API_URL . $endpoint . $this->apiKey;
			$cachedResponse = get_transient( $transient_key );
			if ($cachedResponse !== false) { return $cachedResponse; }
			$response = $this->client->get($endpoint);
			$result = json_decode((string)$response->getBody(), true);
			set_transient( $transient_key, $result, HOUR_IN_SECONDS );
			return $result;
		} catch (RequestException $e) {
			// TODO: pass along error message!
			// http://localhost:8083/wp-json/rds-bt50-scorecard/v1/scorecard
			error_log(print_r($e, true));
			return json_decode('{"error": "Terrible things happened, sorry"}');
		}
	}

}
