<?php
/**
 * @class AmdaAction
 * @version $Id: AmdaAction.php 2976 2015-07-01 15:05:40Z benjamin $
 *
 */


class AmdaAction
{
	private $xmlFiles  = array('localParam' => 'LocalParams.xml', 'remoteParam' => 'RemoteParams.xml',
										'remoteSimuParam' => 'RemoteParams.xml', 'derivedParam' => 'WsParams.xml', 'myDataParam' => 'WsParams.xml',
										'timeTable' => 'Tt.xml', 'catalog' => 'Tt.xml', 'alias' => 'Alias.xml',
										'myData' => 'Files.xml',
										'request' => 'Request.xml', 'condition' => 'Request.xml',
										'bkgWorks' => 'jobs.xml');

	private $user, $amdaStat;

	public function __construct()
	{
		$dd = new UserMgr();
		$this->user = $dd->user;
		if (!defined('NEWKERNEL_DEBUG') || !NEWKERNEL_DEBUG)
					$this->amdaStat = new AmdaStats($dd->user);
	}

	private function getUrlDirs($url)
	{
		//TODO replace by ftp php class methods: ftp_nlist() etc
		require_once "simple_html_dom.php";

		$url = html_entity_decode($url);
		$trimmed_url = trim($url);
		if (strrpos($trimmed_url, "/") == strlen($trimmed_url) - 1)
		{
			if (file_exists("temp.html")) unlink("temp.html");
			exec("wget -O temp.html ".$url);

			$html = file_get_html('temp.html');
			$dirs = $html->find('a[href]');
			foreach ($dirs as $dir)
			{
				$name =  $dir->innertext; //$dir->href;
				$isLeaf = strrpos($name, "/") !== strlen($name) - 1;
				$childrenToReturn[] = array('text' => $name, 'id' => $trimmed_url.$name, 'nodeType' => 'url', 'leaf' => $isLeaf);
			}

		}

		return $childrenToReturn;

	}

/*****************************************************************
*                           PUBLIC FUNCTIONS
*****************************************************************/

	/*
	*   $obj = { id: node.id,  nodeType: node.nodeType }
	*/
	public function getTree($obj) {

		$node = $obj->node;

		// to correct 'restricted' parameters
		if (strpos($node, restricted) !== false)
		{
			$node = str_replace(restricted,"",$node);
		}

		$nodeType = $obj->nodeType;
		$remoteBase = false;
		$isRemoteDataSet = false;

		if ($nodeType == 'url')
		{
			$url = $node == 'root' ? $obj->baseId : $node;
			return  $this->getUrlDirs($url);
		}

		if ($obj->baseId) $remoteBase = true;

		if ($node == 'root' && $remoteBase)  $node = $obj->baseId;

		if ($node == 'root' && !$remoteBase)
		{
			$json_o = json_decode(file_get_contents(DATAPATH.$nodeType.'.json'));
			$childrenToReturn = $json_o->nodes;
		}
		else
		{
			$Dom = new DomDocument("1.0");

			switch ($nodeType)
			{
				case 'sharedtimeTable':
				case 'sharedcatalog':
					$xmlName = SHAREDPATH.'/SharedObjectTree.xml';
					break;
				case 'bkgWorks':
					$xmlName = USERJOBDIR.$this->xmlFiles[$nodeType];
					break;
				case 'source':
					$xmlName = DATAPATH.'RemoteData/'.$obj->baseId.'/base.xml';
					break;
				case 'destination':
					$xmlName = USERWSDIR.'RemoteParams.xml';
					break;
				default:
					$xmlName = USERWSDIR.$this->xmlFiles[$nodeType];
			}

			if ($remoteBase)
			{
				$nodeType = 'remoteParam';
			}

			$Dom->load($xmlName);

			if ($node == "myRemoteSimuData-treeRootNode")
				$node = "myRemoteData-treeRootNode";

			$nodeToOpen = $Dom->getElementById($node);
			$children = $nodeToOpen->childNodes;

			foreach ($children as $child)
				if ($child->nodeType == XML_ELEMENT_NODE)
				{
					$isLeaf = true;

					if ($child->hasChildNodes())
						foreach ($child->childNodes as $grandChild)
							if ($grandChild -> nodeType == XML_ELEMENT_NODE)
							{
									$isLeaf = false;
									break;
							}
					if ($child->tagName == 'folder')  $isLeaf = false;

					//TODO MAKE PROPERLY  as function of nodetype !!!!
					$info = '';
					$id =  $child->getAttribute('xml:id');
					$name = $child->getAttribute('name');
					$help = $child->getAttribute('att');
					if ($child->hasAttribute('dataStart')) $dataStart = $child->getAttribute('dataStart');
					if ($child->hasAttribute('dataStop')) $dataStop = $child->getAttribute('dataStop');

					$specialNode = false;
					$isParameter = false;
					$isAddable =  false;
					$isSimulation = false;
					$rank = null;

					switch ($nodeType)
					{
						case 'bkgWorks':
							$specialNode = true;
							$status = $child->getAttribute('status');
							//     if ($status == 'done') continue;
							$childrenToReturn[] = array('text' => $name, 'id' => $id,'nodeType' => $nodeType, 'leaf' => $isLeaf,
									'pid' => $child->getAttribute('pid'), 'status' => $status,
									'jobType' => $child->getAttribute('jobType'), 'info' => $child->getAttribute('info'));
						break;

						case 'condition':
							$objectMgr = new RequestMgr();
							$info = $objectMgr->getObject($id)->expression;
						break;

						case 'request':
						$objectMgr = new RequestMgr();
						$objplot = $objectMgr->getObject($id);
						for ($i=0; $i < count($objplot->children); $i++)
						{
							for ($j=0; $j < count($objplot->children[$i]->children); $j++)
							{
								$info = $info.' '.$objplot->children[$i]->children[$j]->name;
							}
						}
						break;

						case 'alias':
							$info = $id;
							$id = 'alias_'.$id;
							if ($isLeaf) $isParameter = true;
						break;

						case 'timeTable':
						case 'catalog':
							if ($isLeaf) $info = $child->getAttribute('intervals').' intervals';
						break;

						case 'sharedtimeTable':
						case 'sharedcatalog':
							if ($isLeaf)
							{
								$info = '<b>Nb intervals:</b> '.$child->getAttribute('nbIntervals').'<br/>';
								$info .= '<b>Shared by:</b> '.$child->getAttribute('sharedBy').' ('.$child->getAttribute('sharedDate').')<br/>';
								$info .= '<b>Description:</b> '.$child->getAttribute('description');
							}
						break;
						case 'derivedParam':
							$info = $child->getAttribute('buildchain');
							if ($isLeaf) $isParameter = true;
						break;

						case 'localParam':

							$globalStart = null;
							$globalStop = null;
							$timeRestriction = false;
							$specialNode = true;
							$isParameter = false;
							$needsArgs = false;
							$isSpectra = false;
							$isStack = false;

							if ($child->hasAttribute('desc'))
							{
								$info = $child->getAttribute('desc');

								if ($child->hasAttribute('dataStart') && $child->hasAttribute('dataStop'))
								{
									$info .= "<br/>Time Range: ".$child->getAttribute('dataStart')."-".$child->getAttribute('dataStop');
								}

								if ($child->getAttribute('dataStart') == 'depending on mission')
								{
									$info .= "<br/>Time Range: ".$child->getAttribute('dataStart');
								}

								if ($child->getAttribute('restriction') > 1)
								{
									$restricted  = $child->getAttribute('restriction');
									$info .= "<br/><b>Time Restriction</b>: -$restricted days";
								}
							}

							if ($child->hasAttribute('units')) $info = $child->getAttribute('units');

							if ($child->tagName == 'parameter')
							{
								$isParameter = true;
								$isScatter = true;

								if ($child->parentNode->hasAttribute('dataStart'))
								{
									$globalStart = $child->parentNode->getAttribute('dataStart');
									$globalStop = $child->parentNode->getAttribute('dataStop');
								}

								if ($child->parentNode->getAttribute('restriction') > 1 )
								{
									$timeRestriction = true;

								}
								/*------------------- to show not tested parameters ------*/
								if ($child->getAttribute('tbd'))
									$info .= "<br/><b>Not tested yet</b>";
								/*------------------- --------------------------------------*/
							}

							$component_info = array();
							if ($child->tagName == 'component')
							{
								$isParameter = true;
								$isScatter = true;

								if ($child->parentNode->parentNode->hasAttribute('dataStart'))
								{
									$globalStart = $child->parentNode->parentNode->getAttribute('dataStart');
									$globalStop = $child->parentNode->parentNode->getAttribute('dataStop');
								}

								if ($child->parentNode->parentNode->getAttribute('restriction') > 1)
								{
									$timeRestriction = true;
								}

								if ($child->hasAttribute("index1"))
									$component_info["index1"] = $child->getAttribute('index1');
								if ($child->hasAttribute("index2"))
									$component_info["index2"] = $child->getAttribute('index2');

								$component_info["parentId"] = $child->parentNode->getAttribute('xml:id');
							}

							if ($child->tagName == 'parameter' && $child->hasChildNodes()) $isScatter = false;

							if ($child->tagName == 'parameter' && $child->hasAttribute('display_type'))
							{
								if ($child->getAttribute('display_type') == 'spectrogram')
								{
										$needsArgs = true;
										$isSpectra = true;
										$isScatter = false;
								}
								elseif ($child->getAttribute('display_type') == 'stackplot')
								{
										$isStack = true;
										$isScatter = false;
								}
							}

							if ($isParameter)
							{
								if ($child->tagName == 'parameter' && $child->childNodes->length == 1)
								{
									$needsArgs = true;
								}
								if (substr($id,0,4) == 'bt96' || substr($id,0,6) == 'ba2000'|| substr($id,0,5) == 'bcain' || substr($id,0,7) == 'bmorsch' )
								{
									$needsArgs = true;
								}

								$objectMgr = new AliasMgr();
								$alias = $objectMgr->getAlias($id);

								$childrenToReturn[] = array('text' => $name,'alias' => $alias,
									'id' => $id,'nodeType' => $nodeType, 'info' => $info, "component_info" => $component_info,
									'globalStart' => $globalStart, 'globalStop' => $globalStop, 'timeRestriction' => $timeRestriction,
									'leaf' => $isLeaf, 'isParameter' => $isParameter, 'isScatter' => $isScatter,
									'isSpectra' => $isSpectra,'isStack' => $isStack, 'needsArgs' => $needsArgs, 'help' => $help, 'notyet' => $not_yet);
							}
							else
							{
								if ($child->tagName == 'mission' || $child->tagName == 'observatory')
								{
									$disable = $child->hasAttribute('restriction');
									$rank = $child->getAttribute('rank');
								}
								else
								{
									$disable = $child->hasAttribute('restriction');
								}

								if ($disable)
								{
									if ($disable == 1) {
										$info .=  "<br/><b>Sorry ! Not finished yet...</b>";
									}
									else {
										$disable = false;
									}
								}

								$childrenToReturn[] = array('text' => $name, 'id' => $id,'nodeType' => $nodeType,  'info' => $info,
									'leaf' => false, 'help' => $help, 'disable' => $disable, 'rank' => $rank);
							}
						break;

						case 'remoteSimuParam' :

							$globalStart = null;
							$service_down = false;
							$isSimulation = true;

			            if ($child->getAttribute('isAddable')) // 'spase://IMPEX/SimulationModel/FMI/GUMICS'
							{
								$isLeaf = false;
								$isAddable = true;
							}

							if ($child->tagName == 'dataCenter')
							{
								if ($child->getAttribute('isSimulation'))
								{
									$service_down = !($child->getAttribute('available'));
									break;
								}
								else
								{
									$skip = true;
									break;
								}
							}

							if ($child->hasAttribute('rank'))
							{
								$rank = $child->getAttribute('rank');
							}

							if ( $child->tagName == 'parameter')
							{
								if ($child->parentNode->hasAttribute('globalStart'))
									{
										$globalStart = $child->parentNode->getAttribute('globalStart');
										$globalStop = $child->parentNode->getAttribute('globalStop');
									}
							}

							if ( $child->tagName == 'component')
							{
								if ($child->parentNode->parentNode->hasAttribute('dataStart'))
									{
										$globalStart = $child->parentNode->parentNode->getAttribute('dataStart');
										$globalStop = $child->parentNode->parentNode->getAttribute('dataStop');
									}
							}

						case 'remoteParam' :

							if ($child->getAttribute('isSimulation') && $child->tagName == 'dataCenter')
							{
								$skip = true;
								break;
							}

							$isDeletable = $child->hasAttribute('isDeletable');
							$specialNode = true;
							$isParameter = false;

							$isSpectra = false;

							switch ($id)
							{
								case 'CDAWEB'  :
								case 'OMNIWEB' :
									$isLeaf = false;
									break;
								case 'THEMIS' :
									$rank = 5;
									break;
								case 'MAPSKP' :
									$rank = 9;
									break;
								default:
							}

							$info = $child->getAttribute('desc');

							if ($info && !$isSimulation)
							{
								$info = str_replace(';', "<br/>Time Range: ", $info);
							}

							if (($child->tagName == 'parameter') || ($child->tagName == 'component'))
							{
								$isParameter = true;
								$isScatter = true;
							}

							$needsArgs =  $child->getAttribute('needsArgs');

							if (($child->tagName == 'parameter' && $child->hasChildNodes()) || $needsArgs) $isScatter = false;

							if ($remoteBase)
							{
								if ($child->tagName == 'dataset') $isRemoteDataSet = true;
							}

							if ($isParameter)
							{
								$disable = $child->parentNode->getAttribute('disabled');
								$objectMgr = new AliasMgr();
								$alias = $objectMgr->getAlias($id);

								if ($child->hasAttribute('display_type') && $child->getAttribute('display_type') == 'spectrogram')
								{
									$needsArgs = true;
									$isScatter = false;
									$isSpectra = true;
								}
								if ($globalStart)
								 $childrenToReturn[] = array('text' => $name,'alias' => $alias,
										'id' => $id,'nodeType' => $nodeType,  'info' => $info, 'help' => $help,  'globalStart' => $globalStart,
										'globalStop' => $globalStop, 'leaf' => $isLeaf, 'disable' => $disable, 'isParameter' => $isParameter,
										'isScatter' => $isScatter, 'isSpectra' => $isSpectra, 'needsArgs' => $needsArgs, "component_info" => $component_info);
								else
									$childrenToReturn[] = array('text' => $name,'alias' => $alias,
										'id' => $id,'nodeType' => $nodeType,  'info' => $info, 'help' => $help,
										'leaf' => $isLeaf, 'disable' => $disable, 'isParameter' => $isParameter,
										'isScatter' => $isScatter, 'isSpectra' => $isSpectra, 'needsArgs' => $needsArgs, "component_info" => $component_info);
							}
							else
							{
// 								if ($child->tagName == 'dataCenter')
// 								{
// 									$restricted = ($child->getAttribute('available') != "1");
// 								}
// 								else
// 									$restricted = false;
//
								if ($id == 'CDAWEB' || $id == 'THEMIS'|| $id == 'MAPSKP')
									$restricted = FALSE;

								if ($child->tagName == 'dataset')
								{
									$nonavailable = ($child->getAttribute('disabled'));
								}
								else
								{
									$nonavailable = false;
								}

								if ($nonavailable)
									$info .= "<br/><b>Not available yet</b>";

								if ($child->getAttribute('url'))
									$info .= "<br/>".$child->getAttribute('url');

								if ($child->hasAttribute('obsolete'))
								{
									$info = $child->getAttribute('desc');
									$obsolete = true;
								}
								else
									$obsolete = false;

								$disable = $restricted || $nonavailable || $obsolete;

								$childrenToReturn[] = array('text' => $name, 'id' => $id,'nodeType' => $nodeType,  'isAddable' => $isAddable,
								'info' => $info, 'leaf' => false, 'isRemoteDataSet' => $isRemoteDataSet, 'disable' => $disable,
								'isSimulation' => $isSimulation, 'rank' => $rank, 'isDeletable' => $isDeletable, 'help' => $help);
							}
						break;

						case 'myData' :
							$info = $child->hasAttribute('info') ? $child->getAttribute('info') : $child->nodeValue;
						break;

						case 'myDataParam' :

							$globalStart = null;
							$globalStop = null;
							$specialNode = true;
							$size = $child->getAttribute('size');
							$isScatter = $size == 1;
							$mask = $child->getAttribute('mask');
							$isSpectra = false;

							if ($isLeaf)
							{
									$isParameter = true;
									$info = "Size: ".$size."<br/>".$child->getAttribute('desc')."<br/> Mask: ".$mask;
									$isSpectra = $child->getAttribute('plottype') === 'Spectra';
							}

							if ($child->hasAttribute('desc'))
							{
									$globalStart = substr($child->getAttribute('desc'), 0, 19);
									$globalStop =  substr($child->getAttribute('desc'), 20);
							}

							$childrenToReturn[] = array('text' => $name, 'size' =>  $size, 'id' => $id,
								'globalStart' => $globalStart, 'globalStop' => $globalStop,
								'nodeType' => $nodeType, 'info' => $info, 'isScatter' => $isScatter, 'leaf' => $isLeaf,
								'isParameter' => $isParameter, 'linkedMask' => $mask, 'isSpectra' => $isSpectra);

						break;
						default:
					}

					if (!$specialNode && !$skip)
					{
						if ($child->hasAttribute('desc'))
							$info = $child->getAttribute('desc');

						if ($isSimulation && $service_down)
						{
							$info = "<b>Service is currently down</b>";
						}

						$childrenToReturn[] = array('text' => $name, 'id' => $id, 'nodeType' => $nodeType, 'info' => $info,
													'help' => $help, 'leaf' => $isLeaf, 'isParameter' => $isParameter);
					}
				}
				// if $childrenToReturn we have to return []
				if ($childrenToReturn == null)
				{
					$childrenToReturn = array('nodeType' => $nodeType, 'text' => null);
				}
			}
      return  $childrenToReturn;
	}

	public  function saveTree($obj)
	{
		$paramMgr = new ParamMgr();
		return $paramMgr->saveTree($obj);
	}

	public  function doNothing($obj)
	{
		return array("res" => 'ok');

	}

	public  function deleteFromTree($obj)
	{
		$paramMgr = new ParamMgr();
		return $paramMgr->deleteFromTree($obj);
	}

/*
*  temporary object fromUpload
*/
	public  function getUploadedObject($name, $format, $nodeType)
	{
		switch ($nodeType)
		{
			case 'timeTable' :
				$objectMgr = new TimeTableMgr();
				break;
			case 'myDataParam' :
				$objectMgr = new FilesMgr();
				break;
			case 'catalog' :
				$objectMgr = new CatalogMgr();
				break;
			default:
				return array("error" => $nodeType." NOT_IMPLEMENTED_YET");
		}

		return  $objectMgr->getUploadedObject($name, $format, true);

	}

/*
*  fill ascii file into grid
*/
	public  function getAsciiFile($obj)
	{
		$objectMgr = new FilesMgr();
		return  $objectMgr->getAsciiFile($obj->fileName);
	}

	public function getMyParamInfo($object)
	{
		$objectMgr = new FilesMgr();
		return  $objectMgr->getParamInfo($object);
	}

/*
*  temporary object from Search
*/
	public  function getTmpObject($folderId, $name, $nodeType)
	{
		switch ($nodeType)
		{
			case 'timeTable' :
				$objectMgr = new TimeTableMgr();
			break;
			case 'catalog' :
				$objectMgr = new CatalogMgr();
			break;
			default:
				return array("error" => $nodeType." NOT_IMPLEMENTED_YET");
		}
		return  $objectMgr->getTmpObject($folderId, $name, true);
	}


	public  function getObject($id, $nodeType)
	{
		switch ($nodeType)
		{
			case 'myDataParam':
			case 'derivedParam' :
				$objectMgr = new DerivedParamMgr($nodeType);
				break;
			case 'timeTable' :
			case 'sharedtimeTable' :
				$objectMgr = new TimeTableMgr();
				break;
			case 'catalog' :
			case 'sharedcatalog' :
				$objectMgr = new CatalogMgr();
				break;
			case 'condition' :
			case 'request' :
				$objectMgr = new RequestMgr($nodeType);
				break;
			case 'bkgWorks' :
 				require_once(INTEGRATION_SRC_DIR."RequestManager.php");
				return $this->executeRequest($id, FunctionTypeEnumClass::PROCESSGETINFO);
				break;
			case 'myData' :
				$objectMgr = new FilesMgr();
				break;
			default:
				return array("error" => $nodeType." NOT_IMPLEMENTED_YET");
		}
		return  $objectMgr->getObject($id, $nodeType);
	}

/*
*   $obj = { id: node.id, leaf: node.leaf, nodeType: node.nodeType }
*/
	public  function deleteObject($obj)
	{
		switch ($obj->nodeType)
		{
			case 'myDataParam' :
			case 'derivedParam' :
				$objectMgr = new DerivedParamMgr($obj->nodeType);
				break;
			case 'timeTable' :
				$objectMgr = new TimeTableMgr();
				break;
			case 'catalog' :
				$objectMgr = new CatalogMgr();
				break;
			case 'condition' :
			case 'request' :
				$objectMgr = new RequestMgr($obj->nodeType);
				break;
			case 'alias' :
				$objectMgr = new AliasMgr();
				$obj->id = substr($obj->id,strlen('alias_'));
				break;
			case 'bkgWorks' :
 				require_once(INTEGRATION_SRC_DIR."RequestManager.php");
				return $this->executeRequest($obj, FunctionTypeEnumClass::PROCESSDELETE);

			case 'myData' :
				$objectMgr = new FilesMgr();
				break;
			default:
					return array("error" => $obj->nodeType." NOT_IMPLEMENTED_YET");
		}
		return  $objectMgr -> deleteObject($obj);
	}

/*
*   $obj = { id: node.id, old_name: node.text, name: value,  parent : node.parentNode.id, leaf: node.leaf, nodeType: node.nodeType }
*/
	public  function renameObject($obj)
	{
		switch ($obj->nodeType)
		{

		  case 'myDataParam' :
		  case 'derivedParam' :
			   $objectMgr = new DerivedParamMgr($obj->nodeType);
			   break;
		  case 'timeTable' :
			   $objectMgr = new TimeTableMgr();
			   break;
		  case 'catalog' :
			   $objectMgr = new CatalogMgr();
			   break;
		  case 'condition' :
		  case 'request' :
			   $objectMgr = new RequestMgr($obj->nodeType);
			   break;
		  case 'alias' :
		  	   $objectMgr = new AliasMgr();
		  	   break;
		  default:
			    return array("error" => $obj->nodeType." NOT_IMPLEMENTED_YET");
		}

		return  $objectMgr -> renameObject($obj);
	}

/*
*   $obj = { name: obj.name, obj.nodeType, obj.leaf (??), OBJ DEPENDENT ATTRIBUTES }
*/
	public  function createObject($obj, $folder)
	{
		switch ($obj->nodeType)
		{
			case 'myDataParam' :
			case 'derivedParam' :
				if ($obj->nodeType == 'derivedParam' &&  $this->amdaStat->success)
						$this->amdaStat->addTask('create', $this->user, null);
				$objectMgr = new DerivedParamMgr($obj->nodeType);
				break;
			case 'timeTable' :
				$objectMgr = new TimeTableMgr();
				break;
			case 'catalog' :
				$objectMgr = new CatalogMgr();
			   break;
			case 'condition' :
			case 'request' :
				$objectMgr = new RequestMgr($obj->nodeType);
				break;
			case 'alias' :
				$objectMgr = new AliasMgr();
				break;
			default:
				return array("error" => $obj->nodeType." NOT_IMPLEMENTED_YET");
		}
		return  $objectMgr -> createObject($obj, $folder);
	}

/*
*   $obj = { id:obj.id, name: obj.name, obj.nodeType, obj.leaf (??), OBJ DEPENDENT ATTRIBUTES }
*/
	public  function modifyObject($obj)
	{
		switch ($obj->nodeType)
		{
			case 'myDataParam' :
			case 'derivedParam' :
				$objectMgr = new DerivedParamMgr($obj->nodeType);
				break;
			case 'timeTable' :
				$objectMgr = new TimeTableMgr();
				break;
			case 'catalog' :
				$objectMgr = new CatalogMgr();
				break;
			case 'condition' :
			case 'request' :
				$objectMgr = new RequestMgr($obj->nodeType);
				break;
			default:
				return array("error" => $obj->nodeType." NOT_IMPLEMENTED_YET");
		}
		return  $objectMgr -> modifyObject($obj);
	}
/*
 * {obj.name, obj.nodeType, obj.leaf}
 */
    public function validNameObject($obj) {
		switch ($obj->nodeType) {
			case 'myDataParam' :
			case 'derivedParam' :
				$objectMgr = new DerivedParamMgr($obj->nodeType);
				break;
			case 'timeTable' :
			case 'sharedtimeTable' :
				$objectMgr = new TimeTableMgr();
				break;
			case 'catalog' :
			case 'sharedcatalog' :
				$objectMgr = new CatalogMgr();
				break;
			case 'condition' :
			case 'request' :
				$objectMgr = new RequestMgr($obj->nodeType);
				break;
			default:
				return array("error" => $obj->nodeType." NOT_IMPLEMENTED_YET");
		}

		return  $objectMgr -> validNameObject($obj);
    }

/*
*   Get Jobs en cours
*/
	public  function getJobs()
	{
		require_once(INTEGRATION_SRC_DIR."RequestManager.php");
		return $this->executeRequest($obj, FunctionTypeEnumClass::PROCESSRUNNINGINFO);
	}


	/* AKKA-KERNEL-INT
	Move user check from RequestMgr.php to AmdaAction.php
	*/
	private function checkUser($obj)
	{
		if (defined('NEWKERNEL_DEBUG') && NEWKERNEL_DEBUG)
		{
			$this->user = NEWKERNEL_DEBUG_USER;
			return array('success' => true);
		}


		if (isset($obj->username) && isset($obj->password) && isset($obj->sessionID))
		{
			//$dd = new WSUserMgr();
            //$dd->init($obj->username,$obj->password,$obj->sessionID);
			return array('success' => false, "message" => "AKKA-KERNEL-INT - WS support not implemented");
		}
		else
			$dd = new UserMgr();

		//TODO error handling
		if (($res = $dd -> ddCheckUser()) != 0)
		{
			if ($res == 156)
				return array('success' => false, 'message' => 'Your AMDA session is expired.<br/> Login please!');

			return array('success' => false, 'message' => 'ddLogin error: '.$res);
		}

		if ($dd->user == 'impex')
		{
			//if ($dd->getWsSize() > DISK_QUOTA * 100)
			//	error_log('Natacha! It is time to CLEAN UP IMPEX WS!',1,'nbourrel@irap.omp.eu');
			return array('success' => false, "message" => "AKKA-KERNEL-INT - WS support for IMPEx not implemented");
		}
		else
		{
		// check disk space
			if ($dd->getWsSize() > DISK_QUOTA)
				return array('success' => false, 'message' => 'Please clean up your workspace.<br/>No more space is available');
		}

		$this->user = $dd->user;

		return array('success' => true, 'userHost' => $dd -> getIPclient());
	}

	private function executeRequest($obj, $function)
	{
		$res = $this->checkUser($obj);
		if (!$res['success']) return $res;

		$requestManager = new RequestManagerClass();

		try
		{
			$res = $requestManager->runIHMRequest($this->user, $res['userHost'], $function, $obj);
		} catch (Exception $e)
		{
			return array('success' => false, 'message' => 'Exception detected : '.$e->getMessage());
		}
		return $res;
	}

/*
*    Main EXECUTE PROCEDURE
*/
	public  function execute($node, $obj)
	{
		require_once(INTEGRATION_SRC_DIR."RequestManager.php");

		// just convert TT / Catalog
		if ($obj->nodeType == "download" &&  $obj->downloadSrc == "1")
			return $this->executeRequest($obj, FunctionTypeEnumClass::TTCONVERT);
		else if (isset($obj->action))
			return $this->executeRequest($obj, FunctionTypeEnumClass::ACTION);
		else
		{
			$res = RequestMgr::checkRequest($obj);
			if (!$res['success']) return $res;

			return $this->executeRequest($obj, FunctionTypeEnumClass::PARAMS);
		}
	}

/*
 * Generate derived parameter compilation
 */
	public function compilParam($obj)
	{
		require_once(INTEGRATION_SRC_DIR."RequestManager.php");
		return $this->executeRequest($obj, FunctionTypeEnumClass::PARAMSGEN);
	}

/*
 * Delete derived parameter compilation
 */
	public function compilParamDelete($obj)
	{
		require_once(INTEGRATION_SRC_DIR."RequestManager.php");
		$res = $this->checkUser($obj);

		if (!$res['success'])
			return $res;

		IHMConfigClass::setUserName($this->user);
		$libParamPath = IHMConfigClass::getCompilationPath()."lib/".$obj->paramId.".so";
		if (file_exists($libParamPath))
			unlink($libParamPath);
		return array("success" => true);
	}

/*
 * kill plot process
 */

	public function killPlotRequest()
	{
		require_once(INTEGRATION_SRC_DIR."RequestManager.php");
		return $this->executeRequest((object) array('nodeType' => 'killplot'), FunctionTypeEnumClass::PARAMS);
	}

/*
 * merge time tables
 */
	public  function merge($obj)
	{
		if ($this->amdaStat->success)
			$this->amdaStat->addTask('ttoper', $this->user, null);

		$objectMgr = new TimeTableMgr();

		return  $objectMgr -> merge($obj);
	}


/*
 * intersect time tables
 */
	public  function intersect($obj)
	{
		if ($this->amdaStat->success)
				$this->amdaStat->addTask('ttoper', $this->user, null);

		$objectMgr = new TimeTableMgr();
		$result = $objectMgr -> intersect($obj);

		return  $result;
	}

	public function initTTCache($isCatalog = false, $nparams)
	{
		if (!$isCatalog) $cacheMgr = new TimeTableCacheMgr();
		else              $cacheMgr = new CatalogCacheMgr();

		return $cacheMgr->initTTCache($nparams);
	}


	public function initTTCacheFromTT($id, $type)
	{
		if ($type == 'catalog' || $type == 'sharedcatalog') $cacheMgr = new CatalogCacheMgr();
		else $cacheMgr = new TimeTableCacheMgr();

		return $cacheMgr->initFromTT($id, $type);
	}

	public function initForChart($id, $name, $isTmpObject, $type)
	{
		if ($type == 'catalog' || $type == 'sharedcatalog') $objMgr = new CatalogMgr();

		return $objMgr->initForChart($id, $name, $isTmpObject, $type);
	}

	public function initTTCacheFromTmpObject($folderId, $name, $isCatalog = false)
	{
		if (!$isCatalog) $cacheMgr = new TimeTableCacheMgr();
		else  $cacheMgr = new CatalogCacheMgr();

		return $cacheMgr->initFromTmpObject($folderId, $name);
	}

	public function initTTCacheFromUploadedFile($name, $format, $isCatalog = false)
	{
		if (!$isCatalog) $cacheMgr = new TimeTableCacheMgr();
		else  $cacheMgr = new CatalogCacheMgr();

		return $cacheMgr->initFromUploadedFile($name, $format);
	}

	public function readTTCacheIntervals($o)
	{
		if ($o->typeTT == 'catalog' || $type == 'sharedcatalog') $cacheMgr = new CatalogCacheMgr();
		else $cacheMgr = new TimeTableCacheMgr();

		return $cacheMgr->getIntervals($o->start,$o->limit,$o->sort,$o->filter);
	}

	public function readIntervalsForChart($o)
	{
		if ($o->typeTT == 'catalog' || $type == 'sharedcatalog') $objMgr = new CatalogMgr();

		return $objMgr->getIntervalsForChart($o->id, $o->name, $o->fromPlugin, $o->typeTT);
	}

	public function saveTTCacheIntervalsInTT($o)
	{
		$cacheMgr = new TimeTableCacheMgr();
		return $cacheMgr->saveInTT($o->ttId,$o->action,$o->cacheToken);
	}

	public function addTTCacheInterval($o)
	{
		if ($o->isCatalog) $cacheMgr = new CatalogCacheMgr();
		else $cacheMgr = new TimeTableCacheMgr();

		return $cacheMgr->addInterval($o->index, $o->start, $o->stop);
	}

	public function removeTTCacheIntervalFromId($id, $isCatalog = false)
	{
		if ($isCatalog) $cacheMgr = new CatalogCacheMgr();
		else $cacheMgr = new TimeTableCacheMgr();

		return $cacheMgr->removeIntervalFromId($id);
	}

	public function modifyTTCacheInterval($o)
	{
		if ($o->isCatalog)
		{
			$cacheMgr = new CatalogCacheMgr();
			return $cacheMgr->modifyIntervalFromId($o);
		}
		else $cacheMgr = new TimeTableCacheMgr();

		return $cacheMgr->modifyIntervalFromId($o->cacheId, $o->start, $o->stop);
	}

	public function operationTTCacheIntervals($extendTime, $shiftTime)
	{
		$cacheMgr = new TimeTableCacheMgr();
		return $cacheMgr->operationIntervals($extendTime, $shiftTime);
	}

	public function mergeTTCacheIntervals()
	{
		$cacheMgr = new TimeTableCacheMgr();
		return $cacheMgr->mergeIntervals();
	}

	public function getTTCacheStatistics()
	{
		$cacheMgr = new TimeTableCacheMgr();
		return $cacheMgr->getStatistics();
	}

	public function getTTCacheStatus()
	{
		$cacheMgr = new TimeTableCacheMgr();
		return $cacheMgr->getStatus();
	}

/*
 * Send a feedback
 *
 */
	public function sendFeedback($feed)
	{
		$feedMgr = new FeedbackMgr();
		return $feedMgr->addFeedback($feed->user, $feed->interface, $feed->subject, $feed->userText, $feed->userAgent, $feed->attach);
	}

/*
 * Save state
 *
 */
	public function saveState($datas)
	{
		$myStateMgr = new StateMgr();
		return $myStateMgr->saveState($datas);
	}

/*
 * Load state
 *
 */
	public function loadState($o)
	{
		$myStateMgr = new StateMgr();
		return $myStateMgr->loadState();
	}

/*
 * SAMP
 */
	public function sendToSAMP($o)
	{
		if ($this->amdaStat->success)
			$this->amdaStat->addTask('samp', $this->user, null);

		$objectMgr = new RequestMgr();
		$res = $objectMgr->generateVOTableFromDownloadResult($o->folderId, $o->downId,true,true);
		if ($res['success'])
		{
			foreach ($res['files'] as $key => $value)
			$res['files'][$key] = str_replace(BASE_PATH,"",$value);
		}
		return $res;
	}

/*
 * HST Images
 */
	public function getHstImagesUrl($o)
	{
		if ($this->amdaStat->success)
			$this->amdaStat->addTask('images', $this->user, null);

		$myHstMgr = new HstMgr();
		$res = $myHstMgr->getImagesUrl($o->startTime, $o->stopTime, $o->planet);
		//if ($domRes->length <= 0)
		//	return array('success' => false, 'message' => 'Cannot find HST Images for this request.');
		return array('success' => true, 'result' => $res);
	}

	public function getAPISImagesUrl($o)
	{
		if ($this->amdaStat->success)
			$this->amdaStat->addTask('images', $this->user, null);

		$apisMgr = new APISMgr();
		$res = $apisMgr->get($o->target, $o->startTime, $o->stopTime, $o->datasets);

		return $res;
	}
/*
 * Filters
 */
	public function loadFilterList($o)
	{
		$filtersMgr = new FiltersMgr();
		$res = $filtersMgr->loadList();
		return $res;
	}

	public function loadFilters($o)
	{
		$filtersMgr = new FiltersMgr();
		if (isset($o->id))
			$res = $filtersMgr->loadFilter($o->id);
		else
			$res = $filtersMgr->loadAll();
		return $res;
	}

	public function saveFilter($o)
	{
		$filtersMgr = new FiltersMgr();
		return $filtersMgr->save($o);
	}

	public function createFilter($o)
	{
		$filtersMgr = new FiltersMgr();
		return $filtersMgr->create($o);
	}

	public function destroyFilter($o)
	{
		$filtersMgr = new FiltersMgr();
		$res = $filtersMgr->delete($o);
		return;
	}

	public function getCrtFilterId()
	{
		$filtersMgr = new FiltersMgr();
		$res = $filtersMgr->getCrtId();
		return $res;
	}

	public function getCrtFilterResult()
	{
		$filtersMgr = new FiltersMgr();
		return $filtersMgr->getCrtResult();
	}

	public function setCrtFilterId($o)
	{
		$filtersMgr = new FiltersMgr();
		return $filtersMgr->setCrtId($o->id);
	}

	public function resetFilter()
	{
		$filtersMgr = new FiltersMgr();
		$res = $filtersMgr->reset();
		return $res;
	}

	public function logout($isGuest)
	{
		if ($isGuest)
		{
			$guestMgr = new Guest($this->user);
			$guestMgr->deleteGuest();
		}
		else
		{
			$this->cleanUserWS();
		}
		return;
	}

	public function getInfo($obj)
	{
		if (file_exists(HELPPATH.$obj->name))
		{
			$content = file_get_contents(HELPPATH.$obj->name);
			return  array('success' => true, 'result' => $content);
		}
		return array('success' => false);
	}

	public function getUserInfo()
	{
		$dd = new UserMgr();
		return $dd->getUserInfo();
	}

	public function convertWS()
	{
		$dd = new UserMgr();
		return $dd->convertWS();
	}

	// $obj ={"Object":"Earth","RunCount":"2",
	// "SW_Density_value":"10","SW_Density_weight":"1","SW_Density_scale":"7","SW_Temperature_value":"100", ....}
	public function getRun($obj)
	{
		$myBestRunsMgr = new BestRunsMgr();
		$res = $myBestRunsMgr->getRun($obj);

		return  $res;
	}

	//$obj = array of IDs
	public function addRun($obj)
	{
		$myBestRunsMgr = new BestRunsMgr();

		$ok = $myBestRunsMgr->init();

		if (!$ok)
			return array('success'=>false,'message'=>'cannot init addRun');

		$myBestRunsMgr->addRuns($obj);

		return array('success'=>true,'addedRuns'=>$obj);
	}

	//AKKA - New action to clean user WS
	public function cleanUserWS()
	{
		$this->rrmdir(USERDIR.'DOWNLOAD.TEMP');
		require_once(INTEGRATION_SRC_DIR."RequestManager.php");
		IHMConfigClass::setUserName($this->user);

		// delete impex params and data
		$impexParamMgr = new ImpexParamManager();
		$impexParamMgr->deleteImpexStaff();

		return $this->executeRequest($obj, FunctionTypeEnumClass::PROCESSCLEAN);
	}

	public function rrmdir($dir){
		if (is_dir($dir)) {
			$objects = scandir($dir);
			foreach ($objects as $object) { // Recursively delete a directory that is not empty and directorys in directory
				if ($object != "." && $object != "..") {  // If object isn't a directory recall recursively this function
					if (filetype($dir."/".$object) == "dir")
						$this->rrmdir($dir."/".$object);
					else
						unlink($dir."/".$object);
				}
			}
			reset($objects);
			rmdir($dir);
		}
	}

	public function deleteSpecialInfo($name)
	{
		if (file_exists(USERDIR.$name))
					unlink(USERDIR.$name);
		return array('success' => true);
	}

	public function interactivePlot($obj, $multiPlotState)
	{
		require_once(INTEGRATION_SRC_DIR."RequestManager.php");
		$inputobj = (Object)array(
			'action' => $obj,
			'multiPlotState' => $multiPlotState
		);
		return $this->executeRequest($inputobj, FunctionTypeEnumClass::ACTION);
	}

	public function getParamPlotInit($obj)
	{
		require_once(INTEGRATION_SRC_DIR."RequestManager.php");
		// IMPEX param
		if (preg_match("#^spase___IMPEX_#",$obj->paramId))
			$type = 'impex_plot_init';
		else
		   $type = 'plot_init';

		$inputobj = (Object)array(
				'paramId' => $obj->paramId,
				'type' => $type
		);
		return $this->executeRequest($inputobj, FunctionTypeEnumClass::PARAMINFO);
	}

	public function getParamInfo($obj)
	{
 		require_once(INTEGRATION_SRC_DIR."RequestManager.php");
		// IMPEX param
		if (preg_match("#^spase___IMPEX_#",$obj->paramId))
			$type = 'impex_param_info';
		else
		   $type = 'param_info';

		$inputobj = (Object)array(
				'paramId' => $obj->paramId,
				'type' => $type
		);
		return $this->executeRequest($inputobj, FunctionTypeEnumClass::PARAMINFO);
	}

	public function getSharedObjectFolders($obj)
	{
		$mgr = new SharedObjectsMgr();
		$folders = $mgr->getFolders($obj->type);
		return array('success' => true, 'folders' => $folders);
	}

	public function shareObjects($obj)
	{
		$mgr = new SharedObjectsMgr();
		switch ($obj->type)
		{
			case 'timeTable' :
			case 'catalog' :
				$src_object_path = USERTTDIR.$obj->object->id.".xml";
				break;

			default:
				return array('success' => false, 'message' => 'Unknown object type');
		}

		$result = $mgr->add($obj->type, $obj->name, $obj->folder, $src_object_path, $obj->description, $this->user);
		if (!$result['success'])
			return $result;

		$mgr->updateTree();
		return $result;
	}

	public function isSharedObjectNameAlreadyUsed($obj)
	{
		$mgr = new SharedObjectsMgr();
		$alreadyUsed = $mgr->isNameAlreadyUsed($obj->type, $obj->name);
		return array('success' => true, 'alreadyUsed' => $alreadyUsed);
	}

}
?>