<?php

// 123456 --> /www/beatdb/1/2/3/4/5/123456.json

class BeatDB {
	
	private static $_db_root = '/www/beatdb/';
	
	public static function get($key) {
		if (self::exists($key)) {
			return json_decode(
				file_get_contents(
					self::$_db_root . implode('/', self::getFilePathByKey($key))
				)
			);
		} else {
			return false;
		}
	}
	
	public static function set($key, $data) {
		$path = self::getFilePathByKey($key);
		$part = self::$_db_root;
		for ($i = 0; $i < count($path) - 1; $i++) {
			$part .= $path[$i] .'/';
		}
		if (!file_exists($part)) {
			if (!mkdir($part, 0777, true)) {
				return false;
			}
		}
		file_put_contents($part . $path[$i], json_encode($data));
		chmod($part . $path[$i], 0777);
		return true;
	}
	
	public static function delete($key) {
		$path = self::getFilePathByKey($key);
		$ret = array();
		for ($i = count($path) - 1; $i >= 0; $i--) {
			$part = self::$_db_root . implode('/', $path);
			unset($path[$i]);
			if (is_file($part)) {
				unlink($part);
			} elseif (count(scandir($part)) == 2) {
				rmdir($part);
			}
		}
		return true;
	}
	
	public static function exists($key) {
		return file_exists(self::$_db_root . implode('/', self::getFilePathByKey($key)));
	}
	
	private static function getFilePathByKey($key) {
		$key = strval($key);
		$path = array();
		for ($i = 0; $i < strlen($key) - 1; $i++) {
			$path[] = substr($key, $i, 1);
		}
		$path[] = $key .'.json';
		return $path;
	}
}