<?php
/**
* Manage plugin système trhought php hooks
* @author valentin carruesco
* @category Core
* @license MIT
*/

class Plugin{
	public $id,$name,$author,$link,$licence,$folder,$description,$version,$state,$type,$require,$firms,$color,$icon;

	function __construct(){
		$this->state = false;
	}

	public function toArray(){
		return array(
			'id' => $this->id,
			'name' => $this->name,
			'author' => $this->author,
			'link' => $this->link,
			'licence' => $this->licence,
			'folder' => $this->folder,
			'description' => $this->description,
			'version' => $this->version,
			'state' => $this->state,
			'type' => $this->type,
			'require' => $this->require,
			'firms' => $this->firms,
			'color' => $this->color,
			'icon' => $this->icon
		);
	}

	public static function exist($id){
		foreach(self::getAll() as $plugin)
			if($plugin->id==$id) return true;
		return false;
	}

	public static function addHook($hookName, $functionName){
		$GLOBALS['hooks'][$hookName][] = $functionName;
	}

	public static function callHook($hookName, $hookArguments = array()) {
		if(!isset($GLOBALS['hooks'][$hookName])) return;
		foreach($GLOBALS['hooks'][$hookName] as $functionName)
			call_user_func_array($functionName, $hookArguments);
	}

	public static function includeAll(){
		global $myFirm;
		$validFirm = is_object($myFirm) && is_numeric($myFirm->id) && $myFirm->id!=-1;
		foreach(self::getAll() as $plugin) {
			if(!$plugin->state) continue;
			if($validFirm && !in_array($myFirm->id, $plugin->firms)) continue;

			$main = $plugin->path().SLASH.$plugin->folder.'.plugin.php';
			if(file_exists($main)) require_once($main);
		}
	}

	public static function getAll($enableOnly = false,$includeCore = false){
		$plugins = array();
		foreach(glob(__ROOT__.PLUGIN_PATH.'*'.SLASH.'app.json') as $file){
			$plugin = self::parseManifest($file);
			if($enableOnly && !$plugin->state) continue;
			$plugins[] = $plugin;
		}

		if($includeCore) $plugins[] = self::parseManifest('.');

		usort($plugins, function($a, $b){
			return strcmp($a->name, $b->name);
		});
		return $plugins;
	}

	public static function getById($id){
		$plugin = false;
		foreach(self::getAll() as $onePlugin)
			if($onePlugin->id==$id) $plugin = $onePlugin;
		return $plugin;
	}

	public static function parseManifest($file){

		//Si on cible le coeur
		if($file=='.' || basename(dirname($file)) == 'class'){
			$plugin = new Plugin();
			$plugin->name = 'Coeur logiciel';
			$plugin->id = 'fr.core.core';
			$plugin->folder = '.';
			$plugin->state = true;
			$plugin->firms = array(0);
			$plugin->require = array();
			$plugin->author = 'god';
			$plugin->url = '';
			$plugin->licence = 'copyright';
			$plugin->description = 'Coeur de l\'application';
			$plugin->version = '1.0.0';
			$plugin->core = true;
			$plugin->color ='#222222';
			$plugin->icon = 'fas fa-bullseye';
		//Si c'est un plugin classique
		}else{
			$enabled = self::states();
			$plugin = new self();
			$manifest = json_decode(file_get_contents($file),true);
			if(!$manifest) return $plugin;
			if(!isset($manifest['id']) || !isset($manifest['name']) ) return;
			$plugin->name = $manifest['name'];
			$plugin->id = $manifest['id'];
			$plugin->folder = basename(dirname($file));
			if(isset($enabled[$plugin->id])){
				$plugin->state = true;
				$plugin->firms = $enabled[$plugin->id];
			}
			if(isset($manifest['author'])) $plugin->author = $manifest['author'];
			if(isset($manifest['url'])) $plugin->url = $manifest['url'];
			if(isset($manifest['licence'])) $plugin->licence = $manifest['licence'];
			if(isset($manifest['description'])) $plugin->description = $manifest['description'];
			if(isset($manifest['version'])) $plugin->version = $manifest['version'];
			if(isset($manifest['core'])) $plugin->core = $manifest['core'];
			if(isset($manifest['color'])) $plugin->color = $manifest['color'];
			if(isset($manifest['icon'])) $plugin->icon = $manifest['icon'];
			if(isset($manifest['require'])) $plugin->require = isset($manifest['require']) ? $manifest['require'] : array();
		}
		return $plugin;
	}

	public static function state($id,$state){
		$enabled = self::states();
		$plugin = self::getById($id);

		$main = $plugin->path().SLASH.$plugin->folder.'.plugin.php';
		if(file_exists($main)) require_once($main);

		if($state==0){
			unset($enabled[$plugin->id]);
			Plugin::callHook('uninstall',array($plugin->id));
		} else {
			if(!isset($enabled[$plugin->id])) $enabled[$plugin->id] = array();
			Plugin::callHook('install',array($plugin->id));
		}
		self::states($enabled);
	}

	public static  function states($states = false){
		$enabledFile = File::core().SLASH.'plugin.json';
		if(!file_exists($enabledFile)) touch($enabledFile);
		if(!is_array($states)){
			$enabled = json_decode(file_get_contents($enabledFile),true);
			return !is_array($enabled)?array():$enabled;
		}
		file_put_contents($enabledFile,json_encode($states));
	}

	public static function is_active($id){
		$enabled = self::states();
		return isset($enabled[$id]);
	}

	public function path(){
		if($this->folder=='.') return __ROOT__.SLASH.'class';
		return __ROOT__.PLUGIN_PATH.$this->folder;
	}

	public static function folder($path){
		return str_replace(__ROOT__,'',$path).SLASH;
	}

	public static function url(){
		$bt = debug_backtrace();
		return ROOT_URL.'/'.str_replace(SLASH, '/', PLUGIN_PATH).basename(dirname($bt[0]['file']));
	}

	public static function addCss($css,$options = array('forcePath'=>false)) {
		if(!$options['forcePath']){
			$bt =  debug_backtrace();
			if(substr($css, 0,4) != 'http') $css = str_replace(array(__ROOT__,'\\'),array('','/'),dirname($bt[0]['file'])).$css;
		}
		$GLOBALS['hooks']['css_files'][] = $css;
	}

	public static function callCss($root = null,$cacheVersion = ''){
		if(!isset($GLOBALS['hooks']['css_files'])) return '';
		$stream = '';
		foreach($GLOBALS['hooks']['css_files'] as $css_file){
			$url = $css_file;
			if(isset($root) && substr($css_file,0, 4) != 'http') $url = $root.'/'.$url;
			$stream .='<link rel="stylesheet" href="'.$url.'?v='.$cacheVersion.'">'."\n";
		}
		return $stream;
	}

	public static function addJs($js){
		global $_;
		$bt =  debug_backtrace();
		if(substr($js, 0,4) != 'http') $js = str_replace(array(__ROOT__,'\\'),array('','/'),dirname($bt[0]['file'])).$js;
		$GLOBALS['hooks']['js_files'][] = $js;
	}

	public static function callJs($root = null,$cacheVersion = ''){
		if(!isset($GLOBALS['hooks']['js_files'])) return '';
		$stream = '';

		foreach($GLOBALS['hooks']['js_files'] as $js_file){
			$url = $js_file;
			if(isset($root) && substr($js_file,0, 4) != 'http') $url = $root.'/'.$url;
			$stream .='<script type="text/javascript" src="'.$url.'?v='.$cacheVersion.'"></script>'."\n";
		}
		return $stream;
	}

	/*
	 * Aide à l'inclusion de classes de plugin, ex:
	 * require_once('..'.SLASH.'plugin'.SLASH.'issue'.SLASH.'Event.class.php');
	 * 	devient :
	 * Plugin::need('issue/Event');
	 * Il est possible de faires des inclusions mulitples, ex :
	 * Plugin::need('issue/Event, client/Client, client/ClientContact');
	*/
	public static function need($selectors){
	    foreach(explode(',',$selectors) as $selector){
	        list($plugin,$class) = explode('/',trim($selector));
	        require_once(__ROOT__.PLUGIN_PATH.$plugin.SLASH.$class.'.class.php');
	    }
	}
}
