<?php
class FileType {

	public static function manifest(){
		return array(
			'uid' => 'file',
			'label' => 'Fichiers',
			'description' => 'Fichiers attachés',
			'fromExtension' => array('*'),
			'toExtension' => 'zip',
			'icon' => 'far fa-file-archive',
			'color' => '#ffffff',
			'background' => '#d7332d'
			
		);
	}

	//Import depuis un glisser déposé du fichier
	public static function fromFile($resource){
		// $resource->save();
		// $ext = getExt($resource->label);
		// $name = $resource->id.'.'.$ext;
		// file_put_contents(SKETCH_PATH.$name,$resource->content);
		// $resource->content = $name;
		// return $resource;
	}

	//Import depuis un flux json compressé de la ressource
	public static function fromJson($resource){
		// $resource->save();
		// $stream = base64_decode($resource->content);
		// $resource->content = $resource->id.'.png';
		// file_put_contents(SKETCH_PATH.$resource->content,$stream);
		// return $resource;
	}
	
	//export en fichier JSON compressé de la ressource
	public static function toJson($resource){
		// $resource = $resource->toArray();
		// $resource['content'] = base64_encode(file_get_contents(SKETCH_PATH.$resource['content']));
		// return $resource;
	}

	public static function toFile($resource){
		global $myUser;
		$infos = self::manifest();
		$path = $resource->directory();

		$filename = $resource->label.'-'.time().'.'.$infos['toExtension'];
		$filepath = sys_get_temp_dir().DIRECTORY_SEPARATOR.$filename;
		$zip = new ZipArchive;
		if(file_exists($filepath))unlink($filepath); 
		$res = $zip->open($filepath, ZipArchive::CREATE);
		if ($res === TRUE) {
			foreach(glob($path.'/*') as $f)
				$zip->addFile($f,basename($f));
			
			$zip->close();
		}
	
		
		return array(
			'name'=> slugify($resource->label).'.'.$infos['toExtension'],
			'content' => file_get_contents($filepath)
		);
	}

	
	/* EDITION */
	public static function toHtml($resource,$sketch=null){
		$infos = self::manifest();

		$response = array();
		//.$resource->id
		$files = array();
		
		foreach(glob($resource->directory().SLASH.'*.*') as $file){
			$files[] = array(
				'path' => 'hackpoint'.SLASH.'sketch'.SLASH.$resource->sketch.SLASH.$resource->id.SLASH.utf8_encode(basename($file)),
				'url' => 'action.php?action=hackpoint_download_file&file='.base64_encode('sketch'.SLASH.$resource->sketch.SLASH.$resource->id.SLASH.rawurlencode(basename($file))),
				'name' => utf8_encode(basename($file)),
				'icon' => getExtIcon(getExt($file))
			);
		}
		

		$response['html'] = '
		<div data-type="dropzone" data-label="Faites glisser vo(s) fichier(s) dans cette zone ou cliquez dessus" data-delete="resource_delete_document" data-save="resource_add_document" class="form-control hackpoint-type-file" id="document" name="document">
				'.json_encode($files ).'
			</div>';
		

		return $response;
	}

}
?>