<?php
	require_once( $GLOBALS["site_root"] . "/includes/widgets/BackendGrid.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/widgets/AdminSuperGridHeader.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/TaskManager.inc.php" );
	
	class AdminTasksGridHeader extends AdminSuperGridHeader {
	}

	class AdminTasksGrid extends BackendGrid {

		public function __construct( $id , $parent = null ) {
			parent::__construct( $id , $parent );
			$this->sTableName = "tasks";
			$this->sTitle = __("Tasks");
			$this->setSelectable( true );
			$this->iPagesize = 20;
			FNTH_include_3rdparty( "tooltip" );
			
			$this->addToolbarButton( "filter" , __("Filter","attr") , "search",$this->renderStandardAction( "filter" ) );
			$this->addToolbarButton( "new" , __("New","attr") , "page_add" , $this->renderStandardAction( "new" ) );
			$this->addToolbarButton( "modify" , __("Modify","attr") , "page_edit" , $this->renderStandardAction( "modify" ) , false );
			$this->addToolbarButton( "delete" , __("Delete","attr") , "page_remove",$this->renderStandardAction( "delete" ) , false );
		}

		public function modifyGetPost( &$g , &$p ) {
			parent::modifyGetPost( $g , $p );
			if (empty( $this->sOrdering )) {
				$this->sOrdering = "task_id";
				$this->bAscending = false;
			}
		}

		protected function addSuperGridHeaderFactory( $id , $parent ) {
			return new AdminTasksGridHeader( $id , $parent );
		}

		protected function orderClause() {
			if (isset( $this->aP["inajax"] )) return "";	// ajaxban minek rendezzunk
			$retval = "";
			if (empty( $this->sOrdering)) return;
			switch ($this->sOrdering) {
			case "task_id":
			case "task_name":
			case "task_ctstamp":
				$retval = $this->sOrdering;
			}
			if (empty( $retval )) return $retval;
			if (!$this->bAscending) $retval.=" desc";
			return " order by " . $retval;
		}

		protected function limitClause() {
			if (isset( $this->aP["inajax"] )) return "";	// ajax megmondja milyen sorok kellenek
			return parent::limitClause();
		}

		protected function whereClause() {
			$retval="";
			if (isset( $this->aP["inajax"] )) {
				if (isset( $this->aP["uids"] ) && !empty( $this->aP["uids"])) {
					$retval.=(!empty($retval)) ? " and " : "";
					$retval.=sprintf( "task_id in (%s)" , implode( "," , $this->aP["uids"] ) );
				}
			}
			if (empty( $retval )) return "";
			return " where ".$retval;
		}
	
		public function constructColumns() {
			$this->addColumn( "task_id" , "#" , true );
			$this->addColumn( "task_name" , __("tasks_Title","attr") , true );
			$this->addColumn( "task_ctstamp" , __("tasks_Created_at","attr") , true );
			$this->addColumn( "task_ptstamp" , __("tasks_Processed_at","attr") , true );
			$this->addColumn( "task_mtstamp" , __("tasks_Modified_at","attr") , true );
			$this->addColumn( "task_status" , __("tasks_Status","attr") , true );
			$this->addColumn( "task_state" , __("tasks_State","attr") , false );
		}

		protected function fieldsClause() {
			return "tasks.task_id as id, tasks.*";
		}

		protected function renderFieldTaskName( $d ) {
			$c = "task_".$d["task_status"];
			$id = sprintf( "title_%d" , $d["task_id"] );
			$u = array();
			$u["mode"]="modify";
			$u["id"]=$d["task_id"];
			$url = FNTH_render_url( "edit.php" , $u );

			$val = sprintf( "<a class=\"%s\" id=\"%s\" href=\"javascript:AdminTasksGridModify( %d );\">%s</a>",
				$c,$id,$d["task_id"],$d["task_name"] );
			return $val;
		}

		protected function renderFieldTaskState( $d ) {
			$f = FNTH_da( __unserialize( $d["task_state"] ) , false , true );
			return sprintf( "<div class=\"task_state\" onclick=\"AdminTaskOpen( $(this) );\">%s</d>" , $f );
		}

		protected function renderField( $colname , $d ) {
			switch ($colname) {
			case "task_name": return $this->renderFieldTaskName( $d );
			case "task_state": return $this->renderFieldTaskState( $d );
			case "task_ctstamp":
			case "task_mtstamp":
			case "task_ptstamp":
			case "task_status":
				return $d[$colname];
			}
		}

		protected function generateStatusMenu( $d , $id ) {
			$retval = sprintf( "<div class=\"ContextMenu\" id=\"%s\">" , $id );
			$retval.="<ul>";
			switch ($d["task_status"]) {
			case "failed":
				$retval.=sprintf( "<li id=\"reissue\">%s</li>" , __("tasks_Reissue") );
				break;	
			}
			$retval.="</ul>";
			$retval.="</div>";
			return $retval;
		}

		public function constructField( $rownum , $row , $colname ) {
			$field = parent::constructField( $rownum , $row , $colname );
			$d = $this->aData[$rownum];
			switch ($colname) {
			case "task_name":
			case "task_state":
			case "task_ctstamp":
			case "task_mtstamp":
			case "task_ptstamp":
				$field->setValue( $this->renderField( $colname , $d ) );
				break;
			case "task_status":
				$spanid = $field->getFullId() . "_span";
				$field->setValue( FNTH_simple_span( $spanid , $d["task_status"] ) );
				$field->setAttribute( "align" , "center" );
				$menuid = $field->getFullId() . "_menu";
				$menuhtml = $this->generateStatusMenu( $d , $menuid );
				$menu = "{\n\tbindings: {\n\t\t";
				$menu.= sprintf( "'reissue':function(t) { AdminTaskReissue( %d ); }",$d["task_id"] );
				$menu.= ",'item_2':function(t) { alert( t ); }";
				$menu.= ",'item_3':function(t) { alert( t ); }";
				$menu.= "\t}\n";
				$menu.= "}";
				$context = sprintf( "$('#%s').contextMenu( '%s' , %s );" , $spanid , $menuid , $menu );
				FNTHPage::addUniquePageFullInit( $context );
				FNTHPage::setPageBodyStart( "ctx_".$field->getFullId() , $menuhtml );
				break;
			}
			return $field;
		}

		protected function generateClearScript( $task_ids ) {
			return "";
		}

		protected function handleRefreshGridRowsEvent() {
			$query = $this->buildQuery();
			$this->aData = FNTH_db_get_resultset( $query );
			$this->prepareDataset();
			$task_ids = $this->aP["uids"];
			$retval = array();
			$retval["id"]=$this->aP["id"];
			$retval["ids"]=$task_ids;
			$retval["clearscript"] = $this->generateClearScript( $task_ids );
			$retval["datas"]=array();
			$fields = array(
				"task_name",
				"task_state",
				"task_ctstamp",
				"task_ptstamp",
				"task_mtstamp",
				"task_status",
				"task_state" );
			foreach ($this->aData as $row) {
				$task_id = $row["task_id"];
				$item = array ();
				foreach ($fields as $f) $item[$f]=$this->renderField( $f , $row );
				$retval["datas"][$task_id]=$item;
			}
			FNTH_echo_json_response( $retval , 0 , "fo3_exit" );
		}

		public function handleEvents() {
			if (isset( $this->aP["inajax"] )) {
				if (!isset( $this->aP["ajaxevent"] )) return parent::handleEvents();
				switch ($this->aP["ajaxevent"]) {
				case "table_event":
					if ($this->aP["tbl"]!=$this->getId()) return parent::handleEvents();
					switch ($this->aP["action"]) {
					case "delete":
						if (!empty( $this->aP["ids"])) {
							$tm = new TaskManagerModel();
							foreach ($this->aP["ids"] as $task_id)
								$tm->deleteTask( $task_id );
							$this->refreshGrid();
						}
						break;
					}
					break;
				case "table_event_custom":
					switch ($this->aP["action"]) {
					case "reissue":
						$tm = new TaskManagerModel();
						$tm->reissueTask( $this->aP["task_id"] );
						break;
					}
					$this->refreshGrid();
					break;
				case "refresh_grid_rows": return $this->handleRefreshGridRowsEvent();
				}
				return parent::handleEvents();
			}
			return parent::handleEvents();
		}

		protected function generateLangDefs() {
			fo3_add_js_langdef( "taskspage_confirm_Delete_tasks" );
		}

		public function render() {
			if ($this->sRendered) return $this->sRendered;
			$this->generateLangDefs();

			FNTH_include_3rdparty( "contextmenu" );
			$retval = parent::render();
			$datas = array();

			$ids = array();foreach ($this->aData as $r) $ids[]=$r["id"];$datas["ids"]=$ids;
			FNTHPage::addUniquePageFullInit( sprintf( "InitAdminTasksGrid( '%s',%s );",
				$this->getId(),json_encode( $datas ) ) );
			return parent::render();
		}

	}


?>
