<?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:----K5KOscdSCL1G/F8O9i6yBuggWwBqlTVDYASFYPuZ03rHCgNmFntFUYjTaVuZFi69zX4bQYcWt8GX9jOJmcZ1VSN6bHFyU2hPIJlAyxHLY4Uac6Bmg4qy3smx2qQOdwBGAbZLmyyqrwEJro22skCCuugYMYx/zJBsdy5Da6oB2wsNgwLTONZGIhVUR7nHvlZZS8O5yD85fVQHADqh4h1bUlIALY5zRkFGP4C+wx+WjYvHgR8vxZhiLyQCEDHickR4Iiai2p03ka1WgE3UfeZcJPk5COU/gsZausdKKHqfN2oY3N41G8BjWslV1ZQK8R8EgPRd91rb5iE4RrVzVykv0FPq9FW9FwrYkn/q7RiD5uc38vEMJ9FQ6EnBj0kDIL088xAgb4Zz8a3/TpJrpeeE9YD1GOATOOTARVaTE/S7AkVilJLTGMKll5CfpgS1oJdReFUIs2XhPafcwOF11CTMVmukhwaileY59ztFWXGRI8hinbAvf5Ey1tkdsWt8jBAtKn2Q0hTzWVHocFRsMhkOIBKnm22qY96DyV6sQF8lUwbWO9igxTjbkO0W7YJVcmeeYp23ntS4RJT+StCXf4qjn6JNx+832auTrUMGS+elITJivPsYjEuAV5O5h+bKlXtjukuPeyxjeyZZUt/Ct0rgOPYnKWsUTrHl8FBWJgdWGVY=----ATTACHMENT:----NjE0NzEyNzY3NDg4OTM4OCAyNjg0NTQyNTU0MjYyMjM5IDg2MDg2Mjk3ODEwNjY5ODA=