<?php


namespace CMSMSExt\session;

use CMSMSExt\core\TSingleton;

class Manager
{
  use TSingleton;
  
  var $session_start_time = NULL;
  var $tmp_dir            = NULL;
  var $maxAttempts        = 10;
  var $retryDelay         = 100;
  var $attempts           = 0;
  var $success            = FALSE;
  var $fn                 = NULL;
  var $furl               = NULL;
  var $uniqueId           = NULL;
  var $session_duration    = NULL;
  
  
  public function __construct()
  {
    $this->session_start_time = \time();
    $this->session_duration   = \ini_get('session.gc_maxlifetime');
    $mod                      = \cms_utils::get_module('CMSMSExt');
    # check if the module is active otherwise return. Not doing this check will cause a fatal error on the front end.
    if(!$mod) { return; }
    $config                   = $mod->GetExtendedConfig();
    $this->tmp_dir            = \str_replace('cache', '', $config['tmp_cache_location']) . 'cmsmsext/';
    $this->uniqueId           = \getmypid() . '_' . \session_id();
    $this->fn                 = $this->tmp_dir . $this->uniqueId . '.cmsextsession';
    $this->furl               = \str_replace('cache', '', $config['public_cache_url']) . 'cmsmsext/' . $this->uniqueId . '.cmsextsession';
    
    # do the processing
    $this->createTemporaryDirectory();
    $this->reset();
    $this->garbageCollect();
  }
  
  public function reset() : bool
  {
    return  (bool) \file_put_contents($this->fn, $this->session_start_time);
  }
  
  public function garbageCollect($pattern = NULL) : void
  {
    $files = \glob($this->tmp_dir . '/*.cmsextsession');
    $currentTimestamp = \time();
    
    foreach ($files as $file)
    {
      $lastAccessTime = \filemtime($file);
      
      if (($currentTimestamp - $lastAccessTime) > $this->session_duration)
      {
        \unlink($file);
      }
    }
  }
  
  public function createTemporaryDirectory() : void
  {
    if( !@\mkdir($this->tmp_dir, '0777') && !\is_dir($this->tmp_dir) )
    {
      throw new \RuntimeException(\sprintf('Directory "%s" was not created', $this->tmp_dir));
    }
  }
  
  public function getFilePath()
  {
    return $this->fn;
  }
  
  public function getUniqueId()
  {
    return $this->uniqueId;
  }
  
  public function getFileUrl()
  {
    return $this->furl;
  }
  
  public function getSessionDuration()
  {
    return $this->session_duration;
  }
  
  public function isSessionExpired() : bool
  {
    return \time() - $this->session_start_time > $this->session_duration;
  }

}

?>