<?php
namespace CMSMSExt\FS;

/**
 * Class utils
 *
 * File system utils for CMSMSExt
 *
 * @author Fernando Morgado aka JoMorg
 * @copyright Copyright 2020 - 2022 by Fernando Morgado
 * @package CMSMSExt\FS
 */
final class utils
{
  /**
   * Logs messages to a log file with a datetime stamp ('Y-m-d H:i:s:v')
   * all parameters are optional
   *
   * @param string $message (optional) default: '[empty message]'
   * @param string $folder_name (optional) default: CMSMS root
   * @param string $filename (optional) default 'cmsms_ext'
   *
   * notes: - the file extension is always .log and will be appended to the filename automatically
   *        - if the file doesn't exist it will be created and the top line message will be 'New log file created'
   *        - if it does the messages will be appended to the existing ones.
   */
  public static function log(string $message = '', string $folder_name = '', string  $filename = '') : void
  {
    $datetime    = \date_format(\date_create(), 'Y-m-d H:i:s:v');
    $message     = empty($message) ? '[empty message]' : $message;
    $root        = \dirname(__FILE__, 5);
    $folder_name = empty($folder_name) ? $root : $folder_name;
    $filename    = empty($filename) ? 'cmsms_ext' : $filename;
    $path        = ($root === $folder_name) ? $root : \cms_join_path($root, \str_replace($root, '', $folder_name));
    $file_name   = $filename . '.log';
    $fn          = self::join_path($path, $file_name);
    
    if( !\is_file($fn) )
    {
      $text = $datetime .  ' :: New log file created' . PHP_EOL;
      file_put_contents($fn, $text);
    }
    
    $text  = $datetime . ' :: ';
    $text .= $message . PHP_EOL;
    
    # we try to make sure the line length limit is ignored, and we can log anything we need
    $tmp_max = \ini_set('log_errors_max_len', 0);
    \error_log($text, 3, $fn);
    
    # reset to the old value;
    \ini_set('log_errors_max_len', $tmp_max);
  }
  
  /**
   * Joins and conforms a path
   * from either an array of segments
   * or any number of string parameters
   * with partial paths, directories or filenames
   * 
   * @param mixed ...$segs
   *
   * @return string
   */
  public static function join_path(...$segs)
  {
    if( \is_array($segs[0]) ) { $segs = $segs[0]; }
  
    $path = \implode(\DIRECTORY_SEPARATOR, $segs);
    
    return self::normalize_path($path);
  }
  
  public static function normalize_path(string $path)
  {
    # either MS or other OS uses forward slashes for paths
    # so make sure there are no doubles or mixed slashes
    # except for the required ones
    $t = \explode('://', $path);
    $p = '';
    
    if(\count($t) > 1) # we have a :// protocol pattern
    {
      $p = \array_shift($t) . '://';
    }
    else
    {
      $t = \explode(':\\\\', $path);
      
      if(\count($t) > 1) # we have a :\\ protocol pattern, but really, we want the :// anyway
      {
        $p = \array_shift($t) . '://';
      }
    }
    
    $path = \implode(\DIRECTORY_SEPARATOR, $t);
    $path = \str_replace("\\", '/',  $path);
  
    return $p . \preg_replace('/\/\/+/', '/', $path );
  }
  
}

?>