<?php
global $_,$conf;
switch($_['action']){

	/** SKETCH **/
	//Récuperation d'une liste de sketch
	case 'hackpoint_sketch_search':
		Action::write(function(&$response){
			global $myUser,$_;
			
			require_once(__DIR__.SLASH.'Sketch.class.php');

			
			// OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
			$query = 'SELECT * FROM '.Sketch::tableName().' WHERE 1';
			$data = array();
			//Recherche simple
			if(!empty($_['filters']['keyword'])){
				$query .= ' AND label LIKE ?';
				$data[] = '%'.$_['filters']['keyword'].'%';
			}

			//Recherche avancée
			if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('label'),$query,$data);

			//Tri des colonnes
			if(isset($_['sort'])) sort_secure_query($_['sort'],array('label'),$query,$data);

			//Pagination
			$response['pagination'] = Sketch::paginate(20,(!empty($_['page'])?$_['page']:0),$query,$data);

			$sketchs = Sketch::staticQuery($query,$data,true,0);
			

			
			foreach($sketchs as $sketch){

				if(!$sketch->state &&  $sketch->creator != $myUser->login) continue;

				$row = $sketch->toArray();
				$row['comment'] = truncate($row['comment'],65);
				$row['picture'] = $sketch->picture();
				

				$row['progress-color'] = 'bg-danger';
				if($row['progress'] > 30) $row['progress-color'] = 'bg-warning';
				if($row['progress'] > 45) $row['progress-color'] = 'bg-warning';
				if($row['progress'] > 60) $row['progress-color'] = 'bg-info';
				if($row['progress'] > 75) $row['progress-color'] = '';
				if($row['progress'] > 90) $row['progress-color'] = 'bg-success';


				$row['created'] = relative_time($row['created']);
				$response['rows'][] = $row;
			}
		});
	break;
	
	//Ajout ou modification d'élément sketch
	case 'hackpoint_sketch_save':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('hackpoint','edit')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Sketch.class.php');
			$item = Sketch::getById($_['id']);

			if(isset($_['label'])) $item->label = $_['label'];
			$item->progress = 5;
			if(isset($_['state'])) $item->state = $_['state'] == 'true';
			if(isset($_['comment']))  $item->comment = $_['comment'];
			$item->save();
		});
	break;

	case 'hackpoint_sketch_save_cover':
	Action::write(function(&$response){
		global $myUser,$_;
		
		require_once(__DIR__.SLASH.'Sketch.class.php');
		if(!is_numeric($_['sketch'])) throw new Exception("Sketch non spécifié", 400);
		$sketch = Sketch::provide('sketch');
		if($myUser->login!= $sketch->creator) throw new Exception("Permission insuffisantes", 403);
		
		$folder = $sketch->directory();
		if(!file_exists($folder)) mkdir($folder,0755,true);
		$name = 'cover.jpg';

		$stream = preg_replace('|data\:image\/[^;]*;base64,|is','',$_['stream']);
		$filepath = $folder.SLASH.$name;
		$row = file_put_contents($filepath, base64_decode($stream));
		//Image::resize($filepath,150,150);
		$response['stream'] = 'data:image/jpg;base64,'.base64_encode(file_get_contents($filepath));
		
	});
	break;
	

	case 'hackpoint_sketch_progress_save':
		Action::write(function(&$response){
			global $myUser,$_;
			
			require_once(__DIR__.SLASH.'Sketch.class.php');
			$item = Sketch::getById($_['id']);
			if($myUser->login!=$item->creator) throw new Exception("Permissions insuffisantes",403);
			$item->progress = $_['progress'];
			$item->save();
		});
	break;

	case 'hackpoint_sketch_add':
		global $myUser,$_;
		if(!$myUser->can('hackpoint','edit')) throw new Exception("Permissions insuffisantes",403);
		require_once(__DIR__.SLASH.'Sketch.class.php');
		$sketch = new Sketch();
		$sketch->label = 'Sketch Sans titre';
		$sketch->state = false;
		$sketch->comment = 'Nouveau sketch sans commentaires';
		$sketch->save();

		require_once(__DIR__.SLASH.'Resource.class.php');
		$item = new Resource();
		$item->label = 'Documentation';
		$item->sort = 0;
		$item->type = 'readme';
		$item->content = '# Documentation';
		$item->sketch = $sketch->id;
		$item->save();

		header('location: index.php?module=hackpoint&page=sheet.sketch&id='.$sketch->id);
	
	break;

	//Suppression d'élement sketch
	case 'hackpoint_sketch_delete':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('hackpoint','delete')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Sketch.class.php');
			Sketch::removeById($_['id']);
			
		});
	break;

	
	//Sauvegarde des configurations de hackpoint
	case 'hackpoint_setting_save':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			if(!$myUser->can('hackpoint','configure')) throw new Exception("Permissions insuffisantes",403);
			foreach(Configuration::setting('hackpoint') as $key=>$value){
				if(!is_array($value)) continue;
				$allowed[] = $key;
			}
			foreach ($_['fields'] as $key => $value) {
				if(in_array($key, $allowed))
					$conf->put($key,$value);
			}
		});
	break;
	
	/** RESOURCE **/
	//Récuperation d'une liste de resource
	case 'hackpoint_resource_search':
		Action::write(function(&$response){
			global $myUser,$_;
			
			require_once(__DIR__.SLASH.'Sketch.class.php');
			require_once(__DIR__.SLASH.'Resource.class.php');
			$sketch = Sketch::provide('sketch');
			if(!$sketch->state &&  $sketch->creator != $myUser->login) throw new Exception("Sketch privé", 403);
			
			foreach(Resource::loadAll(array('sketch'=>$_['sketch']),array('sort')) as $resource){
				$row = $resource->toArray();
				$type = $resource->type();
				$row['type'] = $type;
				$response['rows'][] = $row;
			}
		});
	break;

	case 'hackpoint_resource_edit':
		Action::write(function(&$response){
			global $myUser,$_;
			require_once(__DIR__.SLASH.'Sketch.class.php');
			require_once(__DIR__.SLASH.'Resource.class.php');
			require_once(__DIR__.SLASH.'Resource.class.php');
			$item = Resource::provide('id',1);
			$sketch = $item->join('sketch');
			if(!$sketch->state &&  $sketch->creator != $myUser->login) throw new Exception("Sketch privé", 403);

			$response = $item->toHtml();
			$response['resourceType'] = $item->type;
		});
	break;

	//Sauveagrde du contenu d'une resource
	case 'hackpoint_resource_save_content':
		Action::write(function(&$response){
			global $myUser,$_;
			require_once(__DIR__.SLASH.'Sketch.class.php');
			require_once(__DIR__.SLASH.'Resource.class.php');
			$item = Resource::provide('id',1);
			$sketch = $item->join('sketch');
		
			if($sketch->creator != $myUser->login) throw new Exception("Permissions insuffisantes",403);
			$item->content = $_['content'];
			$item->save();
		});
	break;
	
	//Ajout ou modification d'élément resource
	case 'hackpoint_resource_save':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('hackpoint','edit')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Sketch.class.php');
			require_once(__DIR__.SLASH.'Resource.class.php');
			require_once(__DIR__.SLASH.'ResourceType.class.php');
			$item = Resource::provide('id',1);
			$sketch = $item->join('sketch');
			if( !is_object($sketch) || $sketch->id==0){
				$sketch = Sketch::getById($_['sketch']);
			}
			if($sketch->creator != $myUser->login) throw new Exception("Permissions insuffisantes",403);

			if(!isset($_['type']) && $item->id!=0) $_['type'] = $item->type;
			$type = ResourceType::types($_['type']);
			
			if(isset($_['label'])) $item->label = $_['label'];
			if($item->id==0){
				$item->label = $type['label'];
				$item->sort = 100;
				$item->type = $_['type'];
				if(isset($type['default'])) $item->content = $type['default'] ;
				$item->sketch = $_['sketch'];
			}
			
			$item->save();
			$response = $item->toArray();

			$response['type'] = $item->type();
		});
	break;
	
	case 'hackpoint_resource_sort':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('hackpoint','edit')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Sketch.class.php');
			require_once(__DIR__.SLASH.'Resource.class.php');
			require_once(__DIR__.SLASH.'ResourceType.class.php');
			foreach($_['sort'] as $sort=>$id){
				$resource =  Resource::getById($id,1);

				$sketch = $resource->join('sketch');
				if($sketch->creator != $myUser->login) continue;

				$resource->sort = $sort;
				$resource->save();
			}
		});
	break;	

	//Suppression d'élement resource
	case 'hackpoint_resource_delete':
		Action::write(function(&$response){
			global $myUser,$_;
			require_once(__DIR__.SLASH.'Sketch.class.php');
			require_once(__DIR__.SLASH.'Resource.class.php');

	
			$item = Resource::getById($_['id'],1);
			$sketch = $item->join('sketch');
			if($sketch->creator != $myUser->login) throw new Exception("Permissions insuffisantes",403);
			Resource::deleteById($_['id']);
			
		});
	break;

	
	//Sauvegarde des configurations de hackpoint
	case 'hackpoint_setting_save':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			if(!$myUser->can('hackpoint','configure')) throw new Exception("Permissions insuffisantes",403);
			foreach(Configuration::setting('hackpoint') as $key=>$value){
				if(!is_array($value)) continue;
				$allowed[] = $key;
			}
			foreach ($_['fields'] as $key => $value) {
				if(in_array($key, $allowed))
					$conf->put($key,$value);
			}
		});
	break;
	


	//Suppression document
	case 'resource_delete_document':
	Action::write(function(&$response){
		global $myUser,$_;
		if(!$myUser->can('hackpoint','delete')) throw new Exception("Permissions insuffisantes",403);
		require_once(__DIR__.SLASH.'Resource.class.php');
		if(!isset($_['path']) ) throw new Exception("Chemin non spécifié ou non numerique");
		//Le premier argument est un namspace de sécurité 
		//et assure que le fichier sera toujours cloisoné dans un contexte file/hackpoint/sketch
		$path = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? utf8_decode($_['path']) : $_['path'];
		File::delete('hackpoint'.SLASH.'sketch',$path);
	});
	break;

	case 'resource_add_document':
	Action::write(function(&$response){
		global $myUser,$_;
		if(!$myUser->can('hackpoint','edit')) throw new Exception("Permissions insuffisantes",403);
		require_once(__DIR__.SLASH.'Resource.class.php');

		$resource = Resource::provide();
		$folder = $resource->directory();

		if(!file_exists($folder)) mkdir($folder,0755,true);

		foreach ($_['files'] as $file) {

			$name = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? utf8_decode($file['name']) : $file['name'];
			$row = File::move(File::temp().$file['path'],str_replace(File::dir(),'',$folder).SLASH.$name);
			$row['url'] = 'action.php?action=hackpoint_download_file&file='.base64_encode('sketch'.SLASH.$resource->sketch.SLASH.$resource->id.SLASH.rawurlencode($file['name']));
			$row['oldPath'] = $file['path'];

			if(!in_array( getExt($file['name']), array('jpg','jpeg','png','bmp','svg'))){
				$row['icon'] = $file['icon'];//getExtIcon( getExt($file));
			}

			$response['files'][] = $row;
		}
		
	});
	break;




		/** PART **/
	//Récuperation d'une liste de part
	case 'hackpoint_part_search':
		Action::write(function(&$response){
			global $myUser,$_;
			
			require_once(__DIR__.SLASH.'Sketch.class.php');
			require_once(__DIR__.SLASH.'Part.class.php');
			require_once(__DIR__.SLASH.'Resource.class.php');
			require_once(__DIR__.SLASH.'ResourcePart.class.php');

			$item = Resource::provide('resource',1);
			$sketch = $item->join('sketch');
			if(!$sketch->state && $sketch->creator != $myUser->login) throw new Exception("Permissions insuffisantes",403);
			
			foreach(ResourcePart::loadAll(array('resource'=>$_['resource']),  null, null, array('*'),1) as $resourcepart){
				$part = $resourcepart->join('part');
				$row = $part->toArray();
				$row['picture'] = $part->picture(true);
				$row['id'] = $resourcepart->id;
				$row['part'] = $part->id;
				$response['rows'][] = $row;
			}
		});
	break;
	
	//Ajout ou modification d'élément part
	case 'hackpoint_part_save':
		Action::write(function(&$response){
			global $myUser,$_;

			require_once(__DIR__.SLASH.'Sketch.class.php');
			require_once(__DIR__.SLASH.'Part.class.php');
			require_once(__DIR__.SLASH.'Resource.class.php');
			require_once(__DIR__.SLASH.'ResourcePart.class.php');
			
			$item = Resource::provide('resource',1);
			$sketch = $item->join('sketch');
			if($sketch->creator != $myUser->login) throw new Exception("Permissions insuffisantes",403);


			$part = Part::provide('part');
			$part->label = $_['label'];
			if(isset($_['price'])) $part->price = $_['price'];
			if(isset($_['link'])) $part->link = $_['link'];
			if(isset($_['brand'])) $part->brand = $_['brand'];

			$part->state = Part::ACTIVE;
			$part->save();

			if(isset($_['picture'])){
				$stream = base64_decode(preg_replace('|.*image/[^;]*;base64,|i','',$_['picture']));
				$dir = File::dir().'hackpoint'.SLASH.'part'.SLASH.$part->id;
				if(!file_exists($dir)) mkdir($dir,0755,true);
				file_put_contents($dir.SLASH.'cover.jpg', $stream);
			}

			$item =  ResourcePart::provide();
			$item->part = $part->id;
			$item->resource = $_['resource'];
			$item->save();
			$response = $item->toArray();
		});
	break;
	
	
	//Suppression d'élement part
	case 'hackpoint_resource_part_delete':
		Action::write(function(&$response){
			global $myUser,$_;
			//if(!$myUser->can('hackpoint','delete')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Sketch.class.php');
			require_once(__DIR__.SLASH.'Resource.class.php');
			require_once(__DIR__.SLASH.'ResourcePart.class.php');
			require_once(__DIR__.SLASH.'Part.class.php');
			$resourcePart = ResourcePart::getById($_['id'],2);
			$resource = $resourcePart->join('resource');
			$sketch = $resource->join('sketch');
			if($sketch->creator!=$myUser->login) throw new Exception("Permissions insuffisantes",403);
			ResourcePart::deleteById($_['id']);
			
		});
	break;
	//Suppression d'élement part
	case 'hackpoint_part_delete':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('hackpoint','delete')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Part.class.php');
			Part::deleteById($_['id']);
			
		});
	break;


	//Download d'un fichier
	case 'hackpoint_download_file':
		Action::write(function(&$response){
			global $myUser,$_;
			$file = str_replace(array('..'),array(''),urldecode(base64_decode($_['file'])));
			
		
			$file = File::dir().'hackpoint'.SLASH.$file;
			File::downloadFile($file);
		});
	break;


	
	//Sauvegarde des configurations de hackpoint
	case 'hackpoint_setting_save':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			if(!$myUser->can('hackpoint','configure')) throw new Exception("Permissions insuffisantes",403);
			foreach(Configuration::setting('hackpoint') as $key=>$value){
				if(!is_array($value)) continue;
				$allowed[] = $key;
			}
			foreach ($_['fields'] as $key => $value) {
				if(in_array($key, $allowed))
					$conf->put($key,$value);
			}
		});
	break;

	case 'autocomplete_part':

	    	Action::write(function(&$response){
	    		require_once(__DIR__.SLASH.'Part.class.php');
	    		
	        	global $myUser,$_;
        		if (!$myUser->connected()) throw new Exception("Error Processing Request", 1);
        		 new Exception("Vous devez être connecté!");

        		$response['rows'] = array();
				$data = array("%".$_['keyword']."%",0);
	        	$parts = Part::staticQuery('SELECT * FROM {{table}} WHERE label LIKE ? AND state=? LIMIT 10',array("%".$_['keyword']."%",Part::ACTIVE),true);
	        	foreach($parts as $part){
	                $response['rows'][] = array(
	                	'name'=>html_entity_decode($part->label, ENT_QUOTES),
						'id'=>$part->id,
						'picture' => $part->picture()
					);
	        	}
		        
	        	if(isset($_['data']) && isset($_['data']['before']) && isset($_['data']['before'])!=''){
	        		$list = json_decode(html_entity_decode($_['data']['before']),true);
	        		if(is_array($list)){
	        			foreach ($list as $key=>$value) {
	        				if(preg_match('/'.$_['keyword'].'/i', $value))
	        					array_unshift($response['rows'],array('name'=>$value,'id'=>$key));
	        			}
	        		}
	        	}
	        });
	    break;

	    case 'get_part_by_id':
	    Action::write(function(&$response){
	        global $myUser,$_;
        	
        	require_once(__DIR__.SLASH.'Sketch.class.php');
        	require_once(__DIR__.SLASH.'Resource.class.php');
        	require_once(__DIR__.SLASH.'Part.class.php');


	        $part = Part::getById($_['id'],1);

	        $part = !$part ? new Part() : Part::getById($_['id']);
	        	
	        $row = $part->toArray();
	        $row['label'] =  html_entity_decode($row['label'], ENT_QUOTES);

	        if(isset($_['before']) && isset($_['before'])!=''){
        		$list = json_decode(html_entity_decode($_['before']),true);
        		if(is_array($list)){
        			if(isset($list[$_['id']])) $row = array('label' => $list[$_['id']], 'id'=>$_['id']);
        		}
        	}
	        $response['part'] = $row;
	    });
	    break;

	
}
?>