<?php

/**
 * Vvveb
 *
 * Copyright (C) 2020  Ziadin Givan
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

namespace Vvveb\System\Extensions;

use \Vvveb\System\Cache;

class Plugins extends Extensions {
	static function getInfo($file, $name) {
		$params               = parent::getInfo($file, $name);
		$params['screenshot'] = '/plugins/' . $name . '/screenshot.png';

		return $params;
	}

	static function getList($path = '') {
		return parent :: getListInfo(DIR_PLUGINS . '/*/plugin.php');
	}

	static function getActiveList($path = '') {
		return parent :: getListInfo(DIR_PLUGINS . '/*/plugin.php');
	}

	static function loadPlugins($path = '') {
		$plugins = parent :: getList(DIR_PLUGINS . '/*/plugin.php');

		foreach ($plugins as $plugin) {
			include $plugin['file'];
		}
	}

	static function getMarketList($params = []) {
		$cacheDriver = Cache :: getInstance();

		$params['action'] = 'query_plugins';
		$query            = http_build_query($params);

		$cacheKey = md5($query);

		if ($result = $cacheDriver->get($cacheKey)) {
			return $result;
		} else {
			$url = 'http://plugins.vvveb.com/api/plugins.json';

			$ch = curl_init($url);

			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$result = curl_exec($ch);
			curl_close($ch);
			$result = json_decode($result, true);

			$cacheDriver->set($cacheKey, $result);

			return $result;
		}
	}
}
