<?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\Str as Str;

class Extensions {
	const KEY_VALUE_REGEX = '/^([\w ]+):\s+(.+)$/m';

	static function unzip($file) {
		// get the absolute path to $file
		$path = pathinfo(realpath($file), PATHINFO_DIRNAME);

		$zip = new ZipArchive();
		$res = $zip->open($file);

		if ($res === TRUE) {
			// extract it to the path we determined above
			$zip->extractTo($path);
			$zip->close();
			echo "WOOT! $file extracted to $path";
		} else {
			echo "Doh! I couldn't open $file";
		}
	}

	static function getParams($comments) {
		$results = [];

		if (preg_match_all(self :: KEY_VALUE_REGEX, $comments, $matches)) {
			$matches[1] = array_map(function ($key) {
				return str_replace(' ','-',strtolower($key));
			}, $matches[1]);

			$results = array_combine($matches[1], $matches[2]);
		}

		return $results;
	}

	static function getComments($file) {
		foreach (token_get_all(file_get_contents($file)) as $entry) {
			if ($entry[0] == T_DOC_COMMENT || $entry[0] == T_COMMENT) {
				$docComments[] = $entry[1];
			}
		}

		return implode("\n", $docComments);
	}

	static function getInfo($file, $name) {
		$comments = self :: getComments($file);
		$params   = self ::  getParams($comments);

		return $params;
	}

	static function getList($path) {
		$list    = glob($path);
		$plugins = [];

		foreach ($list as $file) {
			$plugins[] = ['file' => $file, 'folder' => Str::match('@/([^/]+)/[a-z]+.php$@', $file)];
		}

		return $plugins;
	}

	static function getListInfo($path) {
		$list    = self :: getList($path);
		$plugins = [];

		foreach ($list as $file) {
			$pluginInfo = static::getInfo($file['file'], $file['folder']);
			$pluginInfo += $file;

			$plugins[] = $pluginInfo;
		}

		return $plugins;
	}
}
