<?php

/*
 @nom: StatisticReport
 @auteur: Idleman (idleman@idleman.fr)
 @description:  Modele de classe pour les plugins
 */

//Ce fichier permet de gérer vos données en provenance de la base de données

class StatisticReport extends Entity{

	public $id ,$label,$color,$icon;
	public $TABLE_NAME = 'statistic_report';
	public $fields = array(
		'id'=>'key',
		'label'=>'string',
		'color'=>'string',
		'icon'=>'string'
	);

	public function widgets(){
		require_once(__DIR__.SLASH.'Widget.class.php');
		return Widget::loadAll(array('report'=>$this->id));
	}

	public function remove(){
		require_once(__DIR__.SLASH.'Filter.class.php');
		require_once(__DIR__.SLASH.'Widget.class.php');
		self::deleteById($this->id);
		Filter::delete(array('report'=>$this->id));
		foreach (Widget::loadAll(array('report'=>$this->id)) as $widget) {
			$widget->remove();
		}
	}

	public static function import($zipFile){
		require_once(__DIR__.SLASH.'Filter.class.php');
		require_once(__DIR__.SLASH.'Connection.class.php');
		require_once(__DIR__.SLASH.'Widget.class.php');
		require_once(__DIR__.SLASH.'WidgetElement.class.php');

		$zip = new ZipArchive();
		if(!$zip->open($zipFile)) throw new Exception("Impossible d'ouvrir l'import");

		$report = new self();
		$report->fromArray(json_decode($zip->getFromName('report.json'),true));
		unset($report->id);
		$report->save();

		$filters = $zip->getFromName('filters.json');
		if($filters!=false){
			foreach(json_decode($filters,true) as $line){
				$filter = new Filter();
				$filter->fromArray($line);
				unset($filter->id);
				$filter->report=$report->id;
				$filter->save();
			}
		}
		$connections = $zip->getFromName('connections.json');
		$connectionsMapping = array();
		if($connections!=false){
			foreach(json_decode($connections,true) as $line){
				$connection = new Connection();
				$connection->fromArray($line);
				$oldId = $connection->id;
				unset($connection->id);

				$existing = Connection::load(array('label'=>$connection->label));
				if($existing) $connection = $existing;


				$connection->save();
				$connectionsMapping[$oldId] = $connection->id;
			}
		}

		for( $i = 0; $i < $zip->numFiles; $i++ ){
		    $stat = $zip->statIndex( $i );
		    if(!preg_match('/([0-9]*)\/widget\.json/i',  $stat['name'],$match)) continue;
		    $folder = $match[1];

		    $widget = new Widget();
			$widget->fromArray(json_decode($zip->getFromName($match[0]),true));

			unset($widget->id);
			$widget->report = $report->id;

			$widget->save();


			for( $u = 0; $u < $zip->numFiles; $u++ ){
				$stat2 = $zip->statIndex( $u );
				if(!preg_match('/'.$folder.'\/element\/.*/i',  $stat2['name'],$match2)) continue;

				$elementJson = json_decode($zip->getFromName($match2[0]),true);
				$type = WidgetElement::getType($elementJson['type']);
				$element = new $type();
				$element->fromArray($elementJson);

				if(isset($element->connection)) $element->connection = $connectionsMapping[$element->connection];

				unset($element->id);
				$element->widget = $widget->id;
				$element->save();

			}


		}


		$zip->close();
	}

	public function export(){
		require_once(__DIR__.SLASH.'Filter.class.php');
		require_once(__DIR__.SLASH.'Connection.class.php');

		$zip = new ZipArchive();
		$file = str_replace('\\\\','\\',File::temp().mt_rand(0,1000).time().'.zip');
		if ($zip->open($file, ZipArchive::CREATE)!==TRUE) throw new Exception("Impossible de créer le zip ".$file);

		$zip->addFromString('report.json', json_encode($this->toArray(),JSON_PRETTY_PRINT));

		$filters = array();
		foreach (Filter::loadAll(array('report'=>$this->id),array('sort')) as $filter) {
			$filters[] = $filter->toArray();
		}
		$zip->addFromString('filters.json', json_encode($filters,JSON_PRETTY_PRINT));
		$connections = array();
		foreach ($this->widgets() as $widget) {
			$zip->addFromString($widget->id.'/widget.json', json_encode($widget->toArray(),JSON_PRETTY_PRINT));
			foreach ($widget->elements() as $i=>$element) {
				if(!empty($element->connection)){
					$connection = Connection::getById($element->connection);
					$connections[$connection->id] = $connection;
				}
				$zip->addFromString($widget->id.'/element/'.$i.'.json', json_encode(array_merge($element->toArray(),array('type'=>get_class($element))),JSON_PRETTY_PRINT));
			}
		}
		$connectionJson = array();
		foreach ($connections as $connection) {
			$connectionJson[$connection->id] = $connection->toArray();
		}
		if(!empty($connectionJson))
			$zip->addFromString('connections.json', json_encode($connectionJson,JSON_PRETTY_PRINT));

	  $zip->close();
	  $stream = file_get_contents($file);
	  unlink($file);
	  return $stream;
	}
}
?>