<?php

namespace elanpl\L3;

class RouteInfo{
    // URL pattern path
    public $path;
    // Http method (ex. GET, POST, ANY)
    public $method;
    // The assigned structure (string, array, function...)
    public $result;
    // The route name
    public $name;
    // BeforeAction event handlers;
    public $beforeAction;
    // AfterAction event handlers;
    public $afterAction;
    // AfterResult event handlers;
    public $afterResult;
       
    public function __construct($method, $path, $result, $name = '')
    {
        $this->path = $path;
        $this->method = $method;
        $this->result = $result;
        $this->name = $name;
        $this->beforeAction = array();
        $this->afterAction = array();
        $this->afterResult = array();
    }

    public function addBeforeAction($event_handler){
        if($this->eventHandlerFormatCheck($event_handler, $match)){
            $this->beforeAction[] = $event_handler;
            return $this;
        }
        else{
            throw new \Exception("Wrong event handler format: $event_handler");
        }
    }

    public function addAfterAction($event_handler){
        if($this->eventHandlerFormatCheck($event_handler, $match)){
            $this->afterAction[] = $event_handler;
            return $this;
        }
        else{
            throw new \Exception("Wrong event handler format: $event_handler");
        }
    }

    public function addAfterResult($event_handler){
        if($this->eventHandlerFormatCheck($event_handler, $match)){
            $this->afterResult[] = $event_handler;
            return $this;
        }
        else{
            throw new \Exception("Wrong event handler format: $event_handler");
        }
    }

    public static function eventHandlerFormatCheck($event_handler, &$match){
        $pattern = '#^((?<class>[a-z0-9\\\\]+)::)?(?<function>[a-zA-Z0-9]+)(\\((?<arguments>[a-zA-Z0-9;, \-/]+)?\\))?$#i';
        if(preg_match($pattern, $event_handler, $match)){
            if(isset($match['arguments'])){
                $result = self::eventHandlerArgumentsFormatCheck($match['arguments'],$arguments_match);
                return $result;
            }
            else{
                return 1;
            }
        }
        else{
            return 0;
        }
    }

    public static function eventHandlerArgumentsFormatCheck($arguments, &$match){
        $match = explode(',', $arguments);
        return $match;
    }

 }