<?php

abstract class WidgetElement extends Entity{
	public $id,$widget,$sort,$label,$slug;
	public $javascript = '';
	public $icon = 'far fa-file';

	public $fields = array( 
		'id'=>'key',
		'widget'=>'int',
		'sort'=>'int',
		'slug'=>'string',
		'label'=>'string'
	);

	function editor(){
		return 'No editor yet';
	}

	function preview(){
		return 'No preview yet';
	}

	public static function getType($type){
		$file = __DIR__.SLASH.'element'.SLASH.ucfirst($type).'.class.php';
		if(!file_exists($file)) throw new Exception ('Invalid widget element');
		require_once($file);
		return $type;
	}


	public static function cascadePreview($type,$id,$filters = array(),$widget){

		$type = self::getType($type);
		$currentElement = $type::getById($id);
		$elements = self::getElementsByWidget($currentElement->widget);

		$data = array();
		if($currentElement != null){
			foreach($elements as $element){
			
				if($currentElement->sort<$element->sort) continue;		

	
				$response = $element->preview($data,$filters,$widget);
				$data[$element->slug] = $response['data'];
			
			}
		}
		return $response;
	}

	public static function getElementsByWidget($id){
		$elements = array();

		foreach(glob(__DIR__.SLASH.'element'.SLASH.'*.class.php') as $file){
			require_once($file);
			$type = str_replace('.class.php','',basename($file));

			foreach($type::loadAll(array('widget'=>$id)) as $element)
				$elements[] = $element;
		}

		usort($elements, function($a,$b){
			if($a->sort < $b->sort) return -1;
			if($a->sort > $b->sort) return 1;
			if($a->sort == $b->sort) return 0;
		});
		return $elements;
	}

	public function toFile($sort){
		return array(
			'filename' => '',
			'stream' => ''
		);
	}

	public static function template($tpl,$data=array(),$emptyIsNull = false){
	   if($emptyIsNull){
		   foreach($data as $key=>$value){
		  	 if($data[$key]=='') unset($data[$key]);
		   }
	   }
	   return template($tpl,$data,true);
	}
}
?>