<?php


//Déclaration d'un item de menu dans le menu principal
function hackpoint_menu(&$menuItems){
	global $_,$myUser;
	if(!$myUser->can('hackpoint','read')) return;
	$menuItems[] = array(
		'sort'=>3,
		'url'=>'index.php?module=hackpoint',
		'label'=>'Hackpoint',
		'icon'=> 'fas fa-wrench',
		'color'=> '#3498db'
	);
	$menuItems[] = array(
		'sort'=>3,
		'url'=>'index.php?module=hackpoint&page=list.part',
		'label'=>'Composants',
		'icon'=> 'fas fa-microchip',
		'color'=> '#3498db'
	);
}

//Cette fonction va generer une page quand on clique sur hackpoint dans menu
function hackpoint_page(){
	global $_,$myUser;



	if(isset($_['module']) && $_['module'] !='hackpoint') return;
	$page = !isset($_['page']) ? 'list.sketch' : $_['page'];
	$file = __DIR__.SLASH.'page.'.$page.'.php';
	if(!file_exists($file)) throw new Exception("Page ".$page." inexistante");
	
	require_once($file);
}

//Fonction executée lors de l'activation du plugin
function hackpoint_install($id){
	if($id != 'fr.idleman.hackpoint') return;
	Entity::install(__DIR__);

}

//Fonction executée lors de la désactivation du plugin
function hackpoint_uninstall($id){
	if($id != 'fr.idleman.hackpoint') return;
	Entity::uninstall(__DIR__);
}

//Déclaration des sections de droits du plugin
function hackpoint_section(&$sections){
	$sections['hackpoint'] = "Gestion des droits sur le plugin hackpoint";
	// $sections['part'] = "Gestion des droits sur l'entité part";
}

//cette fonction comprends toutes les actions du plugin qui ne nécessitent pas de vue html
function hackpoint_action(){
	require_once(__DIR__.SLASH.'action.php');
}

//Déclaration du menu de réglages
function hackpoint_menu_setting(&$settingMenu){
	global $_, $myUser;
	
	if(!$myUser->can('hackpoint','configure')) return;
		
		$settingMenu[]= array(
			'sort' =>1,
			'url' => 'setting.php?section=global.hackpoint',
			'icon' => 'fas fa-angle-right',
			'label' => 'hackpoint Général'
		);

	
}

//Déclaration des pages de réglages
function hackpoint_content_setting(){
	global $_;
	if(file_exists(__DIR__.SLASH.'setting.'.$_['section'].'.php'))
		require_once(__DIR__.SLASH.'setting.'.$_['section'].'.php');
}


//Déclaration des settings de base
//Types possibles : text,select ( + "values"=> array('1'=>'Val 1'),password,checkbox. Un simple string définit une catégorie.
Configuration::setting('hackpoint',array(
        "Général",
        //'hackpoint_enable' => array("label"=>"Activer","type"=>"checkbox"),
));


 function hackpoint_manage_types(&$types){
 	$types = array_merge($types,glob(__DIR__.SLASH.'types'.SLASH.'*.class.php'));
 }


function hackpoint_dav($requested){
	global $conf,$myUser;
	$requested = trim($requested, '/');
	

	if(substr($requested, 0,13)!='dav/hackpoint') return;
	if(empty($requested)) throw new Exception("Unspecified DAV path");


	require_once(__ROOT__.'common.php');
	require_once(__DIR__.SLASH.'VirtualWebDav.class.php');

	$projectPath = preg_replace('|https?\:\/\/'.$_SERVER['HTTP_HOST'].'|i', '', ROOT_URL);

	$server = new VirtualWebDav();
	$server->logs = VirtualWebDav::logPath().SLASH.'dav-logs.txt';
	$server->lockfile = VirtualWebDav::logPath().SLASH.'dav-lock.json';
	$server->root = str_replace('//','/',$projectPath.'/dav/hackpoint/');

	$server->folder = '';

	//Windows cherche desktop.ini a chaque ouverture de dossier pour le custom
	$server->ignoreFiles[] = 'desktop.ini';
	//Tortoise et autre client git d'explorer cherchent les .git a chaques ouverture
	$server->ignoreFiles[] = '.git';



	$server->do['login'] = function($login,$password){
		global $myUser;

		if($myUser->login !=''){
			return $myUser;
		}
		
		$myUser = User::check($login,$password);

		if(!$myUser)
			throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur",401);
		
		if(file_exists('enabled.maintenance') && $myUser->superadmin != 1)
			throw new Exception('Seul un compte Super Admin peut se connecter en mode maintenance',401);
		
		if(!$myUser->connected())
			throw new Exception('Identifiant ou mot de passe incorrect',401);

		if(is_numeric($myUser->preference('default_firm')) && $myUser->haveFirm($myUser->preference('default_firm'))){
			$_SESSION['firm'] = serialize(Firm::getById($myUser->preference('default_firm')));
			if(!$_SESSION['firm'])
				throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur",401);
			
		}else if(count($myUser->firms)!=0){
			$_SESSION['firm'] = serialize(reset($myUser->firms));
			if(!$_SESSION['firm'])
				throw new Exception(" Problème lors de la connexion, veuillez contacter l'administrateur",401);
		}else{
			throw new Exception('Ce compte n\'est actif sur aucune firm',401);
		}			
		
		$myFirm = isset($_SESSION['firm']) ? unserialize($_SESSION['firm']) : new Firm();
		if(!$myFirm)
			throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur",401);

		$_SESSION['currentUser'] = serialize($myUser);
		if(!$_SESSION['currentUser'])
			throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur",401);
	};

	$server->do['delete'] = function($isoPath){
		global $myUser,$conf;
		$utf8Path = utf8_encode($isoPath);
		throw new Exception("Méthode non implémentée",501);
	};

	$server->do['download'] = function($isoPath){
		global $myUser,$_,$conf;
		$utf8Path = utf8_encode($isoPath);

		//pour verfiier si le fichier existe, on récupere son chemin système avec le bon encodage
		$osPath = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? $isoPath: $utf8Path; 


		require_once(__DIR__.SLASH.'Resource.class.php');
		require_once(__DIR__.SLASH.'ResourceType.class.php');

		preg_match_all('/#([0-9]*)/i', $utf8Path,$matches,PREG_SET_ORDER);
		$id = end($matches);
		$id = $id[1];

		$resource = Resource::getById($id);
		$stream = 'not implemented';

		if(!$resource)  throw new Exception("Fichier inexistant",404);

		$type = ResourceType::types($resource->type);
		$stream = $type['class']::toFile($resource);
		$stream = $stream['content'];

	
		return $stream;
	};

	$server->do['edit'] = function($isoPath,$body,$type){
		global $myUser,$conf;
		User::check_access('hackpoint','edit');
		$utf8Path = utf8_encode($isoPath);


		require_once(__DIR__.SLASH.'Resource.class.php');
		require_once(__DIR__.SLASH.'ResourceType.class.php');
		preg_match_all('/#([0-9]*)/i', $utf8Path,$matches,PREG_SET_ORDER);
		$id = end($matches);
		$id = $id[1];

		$resource = Resource::getById($id);

		if(!$resource)  throw new Exception("Fichier inexistant",404);

		if($type!='file')throw new Exception("Non implémenté",501);

		/*$maxSize = $conf->get('document_allowed_size');*/
		$extension = getExt($utf8Path);
		/*$extensions = explode(',',str_replace(' ', '', $conf->get('document_allowed_extensions')));
		if(strlen($body) > $maxSize) throw new Exception("Taille du fichier  trop grande, taille maximum :".readable_size($maxSize).' ('.$maxSize.' octets)',406);
		if(!in_array($extension , $extensions)) throw new Exception("Extension '".$extension."' du fichier ".$path." non permise, autorisé :".implode(', ',$extensions),415);
	
		if($conf->get('document_enable_logs') || $conf->get('document_enable_logs_verbose')) Log::put('Enregistrement fichier '.$utf8Path,'hackpoint');
	*/
		$resource->content = $body;
		$resource->save();
		
	};

	$server->do['move'] = function($isoPath,$isoTo){
		global $myUser,$conf;
		$utf8Path = utf8_encode($isoPath);
		$utf8To = utf8_encode($isoTo);
		User::check_access('hackpoint','edit');
		throw new Exception("Méthode non implémentée",501);
	};

	$server->do['copy'] = function($isoPath,$isoTo){
		global $myUser,$conf;
		$utf8Path = utf8_encode($isoPath);
		$utf8To = utf8_encode($isoTo);
		User::check_access('hackpoint','edit');
		throw new Exception("Méthode non implémentée",501);
		
	};

	$server->do['list'] = function($isoPath,$depth =0){

		global $myUser,$conf;
		$utf8Path = utf8_encode($isoPath);
		require_once(__DIR__.SLASH.'Sketch.class.php');
		require_once(__DIR__.SLASH.'Resource.class.php');
		User::check_access('hackpoint','read');

		$files  = array();
		$file = array();
		$file['label'] = '';
		$file['type'] = 'directory';
		$file['path'] = '';
		$files[] = $file;
		
		if($depth>0){
			if(!empty($utf8Path)){

				preg_match_all('/#([0-9]*)/i', $utf8Path,$matches,PREG_SET_ORDER);
				
				$sketch = Sketch::getById($matches[0][1]);
				if(count($matches)>1){
					$resources = array(Resource::getById($matches[1][1]));
				}else{
					$resources = Resource::loadAll(array('sketch'=>$sketch->id));
				}
				foreach($resources as $resource){

					$type = $resource->type();
					$file = array();

					if(in_array($type['uid'], array('arduino'))  && count($matches)==1 ){
						$file['label'] = $resource->label.' #'.$resource->id;
						$file['type'] = 'directory';
					}else{
						$file['label'] = $resource->label.' #'.$resource->id.'.'.$type['toExtension'];
						$file['type'] = 'file';
					}

					$file['create_time']  = $resource->created;
					$file['update_time']  =  $resource->updated;
					$file['length'] =  strlen($resource->content);
					$files[] = $file;
				}
			}else{
				foreach(Sketch::loadAll() as $sketch){
					$file = array();
					$file['label'] = $sketch->label.' #'.$sketch->id;
					$file['type'] = 'directory';
					$file['create_time']  = $sketch->created;
					$file['update_time']  =  $sketch->updated;
					$file['length'] =  1;
					$files[] = $file;
				}
			}
		}
		


		return $files;
	};

	$server->start();
}

//Déclation des assets
Plugin::addCss("/css/main.css?v=1"); 
Plugin::addCss("/css/codemirror.css?v=1"); 
Plugin::addCss("/css/codemirror-monokai.css?v=1"); 
Plugin::addCss("/css/component.css?v=1",true); 
Plugin::addCss("/css/animate.min.css"); 

Plugin::addJs("/js/main.js?v=1"); 
Plugin::addJs("/js/codemirror.js?v=1"); 
Plugin::addJs("/js/component.js?v=2",true); 

foreach(glob(__DIR__.SLASH.'js'.SLASH.'codemirror-mode'.SLASH.'*.js') as $file){
	Plugin::addJs("/js/codemirror-mode/".basename($file)); 
}


//Mapping hook / fonctions
Plugin::addHook("install", "hackpoint_install");
Plugin::addHook("uninstall", "hackpoint_uninstall"); 
Plugin::addHook("section", "hackpoint_section");
Plugin::addHook("menu_main", "hackpoint_menu"); 
Plugin::addHook("page", "hackpoint_page");  
Plugin::addHook("action", "hackpoint_action");  
Plugin::addHook("menu_setting", "hackpoint_menu_setting");    
Plugin::addHook("content_setting", "hackpoint_content_setting");   
Plugin::addHook("hackpoint_resource_type", "hackpoint_manage_types");   
 Plugin::addHook("rewrite", "hackpoint_dav");

?>