<?php
/**
 * Define a dashboardwidget.
 * @author Administrateur
 * @category Plugin
 * @license copyright
 */
class DashboardWidget extends Entity{
	public $id,$minified,$position,$model,$dashboard,$title,$icon,$background,$width,$load,$configure,$configure_callback,$configure_init,$move,$delete,$options,$js,$css,$content,$data,$description,$defaultWidth;
	protected $TABLE_NAME = 'dashboard_dashboard_widget';
	public $fields =
	array(
		'id' => 'key',
		'model' => 'string',
		'data' => 'longstring',
		'position' => 'int',
		'minified' => 'boolean',
		'width' => 'int',
		'dashboard' => 'int'
	);

	function __construct(){
 		parent::__construct();
 		$this->options = array();
 		$this->icon = 'fa-caret-right';
 		$this->title = 'Sans titre';
 		$this->defaultWidth = 4;
 		$this->width = 0;
 	}

 	public function toArray($decoded= false){
		$fields = parent::toArray($decoded);
		$fields['options'] = $this->options;
		$fields['icon'] =  $this->icon;
		$fields['background'] =  $this->background;
		$fields['load'] =  $this->load;
		$fields['configure'] =  $this->configure;
		$fields['configure_callback'] =  $this->configure_callback;
		$fields['configure_init'] =  $this->configure_init;
		$fields['js'] =  $this->js;
		$fields['css'] =  $this->css;
		$fields['description'] =  $this->description;
		$fields['content'] =  $this->content;
		$fields['title'] =  $this->title;
		return $fields;
 	}

 	function data($key=null,$value=null){
 		$data = json_decode($this->data,true);
 		if($key==null) return $data;
 		if(is_array($key) && $value==null){
 			foreach ($key as $k => $v) {
 				$data[$k] = $v;
 				$this->data = json_encode($data);
 			}
 			return true;
 		}
 	
 		if($value===null) return isset($data[$key])?$data[$key]:'';
 		
 		$data[$key] = $value;

 		$this->data = json_encode($data);
 		return true;
 	}

 	public static function current(){
 		global $_;
 		$dbWidget = self::getById($_['id']);

 		$widget = DashboardWidget::models($dbWidget->model);
 		$widget->id = $dbWidget->id;
 		$widget->position =  $dbWidget->position;
 		$widget->minified =  $dbWidget->minified;
 		$widget->width = $dbWidget->width;
 		$widget->dashboard = $dbWidget->dashboard;
 		$widget->data = $dbWidget->data;

 		return $widget;
 	}

 	public static function models($modelUid = null){
 		Plugin::callHook('widget',array(&$models));

		foreach($models as $model)
			$models[$model->model] = $model;

		if(!isset($modelUid)) return $models;
		
		return isset($models[$modelUid]) ? $models[$modelUid] : array();
 	}
}
?>