<?php
namespace apexl\Io\services;

use apexl\ClassEngine\EngineSingleton;

class pathUtility extends EngineSingleton {

    protected $currentPathData;

    protected function __construct()
    {
        parent::__construct();
        $this->setCurrentPath();
    }

    /**
     * Function to get either the full path, or a single element of it.
     * @param bool $position
     * @return string
     */
    public function getPath($position = FALSE){
        if($position !== FALSE){
            return $this->currentPathData['path_items'][$position] ?? '';
        } else {
            return $this->currentPathData['full_path'];
        }
    }

    /**
     * Function to set the current path based on the request.
     */
    protected function setCurrentPath(){
        $pathInfo = pathinfo($_SERVER['REQUEST_URI']);
        $fullPath = $pathInfo['dirname'] != DIRECTORY_SEPARATOR ? ltrim($pathInfo['dirname'].DIRECTORY_SEPARATOR.$pathInfo['basename'], DIRECTORY_SEPARATOR) : ltrim($pathInfo['dirname'].$pathInfo['basename'], DIRECTORY_SEPARATOR);
        $pathItems = $pathInfo['dirname'] != DIRECTORY_SEPARATOR ? explode(DIRECTORY_SEPARATOR, strtok($fullPath, '?')) : [strtok($fullPath, '?')];
        $this->currentPathData = [
            'full_path' => $fullPath,
            'path_items' => $pathItems,
            'no_path_items' => count($pathItems),
            'endpoint' => $pathInfo['basename']
        ];
    }
}