<?php

/**
 * manage a file queue into protected/runtime/$name
 * @author p.treu
 *
 */
class RuntimeQueue extends RuntimeFolder
{

  public function __construct($name)
  {
    parent::__construct ( $name );
  }

  /**
   *
   * @return string
   */
  protected function createId()
  {
    return "" . DateTimeEx::now ()->toFilesafeDateTimeString () . "_" . uniqid ();
  }

  /**
   *
   * @param string $value
   *          default=null
   * @return string
   */
  public function add($value = null)
  {
    $id = $this->createId ();
    $itemPath = $this->getPath ( $id );
    file_put_contents ( $itemPath, serialize ( $value ) );
    return $id;
  }

  /**
   *
   * @param string $id          
   * @return string
   */
  public function getPath($id)
  {
    return pathCombine ( $this->path, $id );
  }

  /**
   *
   * @return multitype:string
   */
  public function getRequests()
  {
    $requests = array ();
    foreach ( $this->getFiles () as $file )
      $requests [] = basename ( $file );
    return $requests;
  }

  /**
   *
   * @param string $id          
   * @return boolean
   */
  public function exists($id)
  {
    return fileExists ( $this->getPath ( $id ) );
  }

  /**
   *
   * @param string $id          
   * @return boolean
   */
  public function remove($id)
  {
    if ($this->exists ( $id ))
      return unlink ( $this->getPath ( $id ) );
    return false;
  }

  /**
   *
   * @param string $id          
   * @param string $default
   *          default=null
   * @return mixed
   */
  public function getValue($id, $default = null)
  {
    if ($this->exists ( $id ))
      return unserialize ( file_get_contents ( $this->getPath ( $id ) ) );
    return $default;
  }

  /**
   *
   * @return string
   */
  public function popId()
  {
    $reqs = $this->getRequests ();
    if (count ( $reqs ) > 0)
    {
      sort ( $reqs );
      $first = array_first ( $reqs );
      if ($this->remove ( $first ))
        return $first;
    }
    return null;
  }

  /**
   *
   * @return string
   */
  public function popValue()
  {
    $reqs = $this->getRequests ();
    if (count ( $reqs ) > 0)
    {
      sort ( $reqs );
      $first = array_first ( $reqs );
      if ($this->remove ( $first ))
      {
        return unserialize ( file_get_contents ( $this->getPath ( $first ) ) );
      }
    }
    return null;
  }
}