<?php 


namespace Webfan;

use Webfan\DescriptorType;
use Webfan\RuntimeInterface;
use Webfan\ConfigType;
use Webfan\ExecutionContextType;

use Webfan\Batch;
use Webfan\Baum;

use League\Pipeline\PipelineBuilder;

use League\Pipeline\Pipeline;
use League\Pipeline\StageInterface;

use frdlweb\StubHelperInterface;
use frdlweb\StubRunnerInterface;
use Frdlweb\WebAppInterface; 

use InvalidArgumentException;

/*
			$sequence = new Batch(\get_class($this));
			$sequence->setTimezone();
			$sequence->detect();
			$sequence->getENV();
			$sequence->Application->config(); 
			$sequence->Application->Modules->load();        
			$sequence->Autoloader->register();
			$sequence->loadContainer();        
			$sequence->setApplication = [$sequence->Application];
			$sequence->Requesthandler->handleCliRequest();
			$sequence->Requesthandler->handleHttpRequest();
			
			
			            $parent = $this->getParentForNode($node);

            $parent->children[] = $node;

            $node->parent = $parent;
			*/
class Engine implements ProgramInterface {//RuntimeInterface, 
	
	
	//use \Webfan\ngModuleTrait;
	
   protected $currentProcessorContextType = null;
   protected $Batch = null;
   protected $DataPayload = null;
   protected $ProgramPayload = null;
   protected $OID_TABLE = null;
	
	public function configure(?ConfigType $configurator = null, $payload)
	{
        match($configurator){
			ConfigType::Batch    =>    $this->withConfigurationBatch($payload),
			default => $this->withConfiguration($payload),
        };				
	}
	
	public function load(  $payload){
	  return $this->loadWebApp($payload);
    }	
	
 	/* 
	public function load(DescriptorType $program, $payload){
	//	print_r($payload);die();
        match($program){
         //   DescriptorType::Pipeline      =>    parent::__construct("Bad Request - Invalid Method", 400),
            DescriptorType::WebApp    =>    $this->loadWebApp($payload),
       //    DescriptorType::Timeout            =>    parent::__construct("Bad Request - Timeout", 400)
			DescriptorType::Batch    =>    $this->loadBatch($payload),
		//	default => null !== $this->currentProcessor ? $this->currentProcessor->load($payload) : $this->add($payload),
			//$this->$currentProcessorContextType
			default => $this->defaultLoad($payload),
        };		
    }

		case START_PROGRAM = <<<STARTPROGRAM
 $
 load
 launch
 configure
  handle
   - http
   - cli
STARTPROGRAM;
	case load = 'load';
#	case bootstrap = 'bootstrap';
	case compile = 'compile';
	case update = 'update';
	case install = 'install';
	case uninstall = 'uninstall';
	case build = 'build';
	case handle = 'handle';
	case configure = 'configure';
	case cli = 'cli';
	case http = 'http';
	case httpsession = 'http-session';
	case browser = 'browser';
	case webworker = 'webworker';
	case worker = 'worker';
	case transport = 'transport';
	*/
	public function process(?ExecutionContextType $ExecutionContextType = null, ...$payload)
	{
        match($ExecutionContextType){
		    ExecutionContextType::handle    =>    $this->defaulExecutionHandlerWith($payload),
		    ExecutionContextType::http    =>    $this->defaulExecutionHandlerWith($payload),
			default => $this->defaulExecutionHandlerWith($payload),
        };			
	}
	
	public function defaulExecutionHandlerWith($payload)
	{
		 $AppLauncher = new \Webfan\AppLauncherLegacy(\frdl\r\f::i()->StubRunner); 
		return $this->loadWebApp($AppLauncher);
	}	 
	public function build(?DescriptorType $program = null, ...$payload)
	{
		print_r($payload);
	}	
	public function withConfiguration($payload)
	{
		 print_r($payload);
	}	 	
	public function withConfigurationBatch($payload)
	{
 print_r($payload);
	}	  
	
	
	public function batch( Batch $newBatch = null ) : Batch
   {
	  if(null === $this->Batch){
		   $this->Batch =new Batch();
	  }
	
	   if(null !== $newBatch){
		   $this->Batch =new Batch($this->Batch->{'@@@'}.' -> '.$newBatch->{'@@@'},
								  $this->Batch->{'.'},
								  array_merge($this->Batch->{'@@'},
											 $newBatch->{'@@'}));
	   }
	   
	   return $this->Batch;
   }

	
   public function info( Baum $newBatch = null ) : Baum
   {
	  if(null === $this->OID_TABLE){
		   $this->OID_TABLE =new Baum('ProgramDescriptors', Baum::class);
	  }
	
	   if(null !== $newBatch){
		   $this->OID_TABLE->children[] = $newBatch;
		   $newBatch->parent = $this->OID_TABLE;
	   }
	   
	   return $this->OID_TABLE;
   }	
	
	
   public function program( Baum $newBatch = null ) : Baum
   {
	  if(null === $this->ProgramPayload){
		   $this->ProgramPayload =new Baum('ProgramDescriptors', Baum::class);
	  }
	
	   if(null !== $newBatch){
		   $this->ProgramPayload->children[] = $newBatch;
		   $newBatch->parent = $this->ProgramPayload;
	   }
	   
	   return $this->ProgramPayload;
   }	

	
   public function data( Baum $newBatch = null ) : Baum
   {
	  if(null === $this->DataPayload){
		   $this->DataPayload =new Baum('DataDescriptors', Baum::class);
	  }
	
	   if(null !== $newBatch){
		   $this->DataPayload->children[] = $newBatch;
		   $newBatch->parent = $this->DataPayload;
	   }
	   
	   return $this->DataPayload;
   }	
	
	

	

	public function defaultLoad($payload)
	{
		print_r(__METHOD__);
		print_r($payload);
	}	
	

	public function loadBatch($payload)
	{
		 return ($this->batch(is_object($payload) && !is_null($payload) && true === $payload instanceof Batch
							? $payload : null))->load(is_object($payload) && !is_null($payload) && true === $payload instanceof Batch
							? null : $payload);
	}		

	
	
	
	
	
	public function loadWebApp(StubHelperInterface | WebAppInterface | StubRunnerInterface $payload){
		if($payload instanceof WebAppInterface){
			$AppLauncher =$payload;
		}elseif($payload instanceof StubRunnerInterface){
			$AppLauncher = new \Webfan\AppLauncherLegacy($payload); 
		}elseif($payload instanceof StubHelperInterface){
			$AppLauncher = new \Webfan\AppLauncherLegacy($payload->getRunner()); 
		}else{
			throw new InvalidArgumentException(sprintf('Invalid parameter in %s payload of %s given but %s expected',
													  __METHOD__,
													  is_object($payload) && !is_null($paylod) ? \get_class($payload) : gettype($payload),
													  'one of StubHelperInterface | WebAppInterface | StubRunnerInterface'));
		}
	 

    if(\method_exists($AppLauncher, 'launch')){
	   $AppLauncher->launch();
	}elseif(!$AppLauncher->KernelFunctions()->isCLI() ){
		   $response = $AppLauncher->handle($AppLauncher->getContainer()->get('request'));
		   if(is_object($response) && $response instanceof \Psr\Http\Message\ResponseInterface){ 
			   (new \Laminas\HttpHandlerRunner\Emitter\SapiEmitter)->emit($response);
		   }
	   }elseif($AppLauncher->KernelFunctions()->isCLI() ){
		 return $AppLauncher->handleCliRequest();
	   }else{
	     throw new \Exception('Could not handle request ('.\PHP_SAPI.')');	
       }	
	}
	
	

}__halt_compiler();----SIGNATURE:----rLxL5TZEH4FiTKU4p2DJ/wgHpxKjiUx6p/7TEbpHlTtuwVQudfIuVSwNsNQAC8kQN4cRXCztJQeZO47PhaEv4f7lnmQVXMJw+hO9bVpu1O6JYnCVrJlb2d9ljdJfv6m6fu5WTJ5Q+3CjhyrBseNO2JjiarO9v1lq6GKxlIZWXtEAqVQIG/xaGZl7n5XmHi/8e2RXRF04lR1sMrzUIwx62mAY0LNHIS/6vHoNuJslBr1/svRaZhNeDTyaT9WHO/2/LJ88A8vODs0+d+3McjCzdT40wBkj7Tyn9NKtETAihJpZ3mt25l+EJtYtpddfrgNyLq3Cgmhn7kC93U6WGqc78NabV4DWUUb2nbW1WKqNQ+4wopIig9T4JnnXPpu2atsxruS01MZ/E9oAStmKzjsfAvH0sojA1+i6F5A6gtp2BKzvTKqDNw+zdwCUAbDXJAzW7f/vPPYfnwcfK+dqaGi+JKNUlvvMd5XcT+zmSO83CsgREZFHmzZAFd9s9e+CqD9t4mNiY91mME/7xZNE6SPK9ccV1XStk5LuZkTgcx3IGh37a9ZIcHjs28YflXAF2yx+qO+3zGByMuQjHGFLeV8Z/CVScjk/BDUZB14cvsWFBKi4FIafS92ynsIIlVQ/tG6BnTC9nsdK/EqOST0CLmOGFlCNl5nSUVcXZTyIdnSJYlo=----ATTACHMENT:----NjkyNDcyNTE4OTQxMDkyNyA0MTgwMjc5NTYzMDAzOTMzIDMxNTA5MDc0MDcyNDk2Mjk=