<?php
require_once(dirname(__FILE__)."/icache.php");
class adcAPI{
	private $endpoint = false;
	private $cache = false;

	public function __construct($endpoint, $key, iadcCache $cache = NULL)
	{
		$this->endpoint = $endpoint;
		$this->cache = $cache;
	}

	private function _request($name, $args)
	{
		$url = "/".$name."?".http_build_query($args);
		if ($this->cache){
			$key = md5($url);
			if ($this->cache->exists($key)){
				return json_decode($this->cache->get($key), true);
			}
		}
		//_d($this->endpoint.$url);
		$res = @file_get_contents($this->endpoint.$url);
		if (!$res){
			echo "API error: ".$this->endpoint.$url;
		}
		if ($this->cache){
			$key = md5($url);
			$this->cache->set($key, $res);
		}
		$res = json_decode($res, true);
		return $res;
	}

	public function plugin_info()
	{
		$res = $this->_request("plugin_info", array());
		return $res;		
	}

	public function search($query="", $category=0, $vendor = "")
	{
		$res = $this->_request("search", array("q" => $query, "category"=>$category, "vendor" => $vendor));
		//_d($res);
		return $res;
	}

	public function categories()
	{
		$res = $this->_request("categories", array());
		return $res;
	}

	public function product($product_uid)
	{
		$res = $this->_request("product", array("uid" => $product_uid));
		return $res;		
	} 

	public function settings()
	{
		$res = $this->_request("settings", array());
		return $res;		
	} 

}