<?php

class MapshotRepository extends ModelRepository
{
  private static $_singletonInstance = null;

  public function __construct()
  {
    parent::__construct('Mapshot');
  }

  /**
   * Returns an initiated MapshotRepository
   *
   * @return MapshotRepository
   */
  public static function getInstance()
  {
    if (self::$_singletonInstance === null)
    {
        self::$_singletonInstance = new MapshotRepository();
    }

    return self::$_singletonInstance;
  }


  /**
   * Get mapshot object by id
   *
   * @param  int $id
   * @return Mapshot
   */
  public function getObjectById($id)
  {
    if (!isInt($id))
    {
        return new Mapshot(0);
    }

    static $cache = array();
    $key = $id;
    if (!isset($cache[$key]))
    {
        $cache[$key] = $this->getObjectFromSql('select *, UNIX_TIMESTAMP(time_travel_date) AS map_date from mapshots where id = ? LIMIT 1', [$id]);

        // Use onmy time travel timestamp
        $cache[$key]->timeTravelDate = $cache[$key]->mapDate;
        unset($cache[$key]->mapDate);
    }
    return $cache[$key];
  }


  /**
   * Get all mapshots by user id
   *
   * @param  int $id
   * @return Mapshot
   */
  public function getObjectListByUserId($user_id)
  {
    if (!isInt($user_id))
    {
        return new Mapshot(0);
    }

    static $cache = array();
    $key = $user_id;
    if (!isset($cache[$key]))
    {
        $cache[$key] = $this->getObjectListFromSql('select *, UNIX_TIMESTAMP(time_travel_date) AS map_date from mapshots where user_id = ?', [$user_id]);

        foreach($cache[$key] AS &$mapshot)
        {
          // Use onmy time travel timestamp
          $mapshot->timeTravelDate = $mapshot->mapDate;
          unset($mapshot->mapDate);
        }
    }
    return $cache[$key];
  }


  /**
   * Returns an object based on the provided sql
   *
   * @param  string $sql
   * @param  array  $arg
   * @return StandardItem
   */
  public function getObjectFromSql($sql, $arg)
  {
    $pdo = PDOMysqlConnection::getInstance();

    $stmt = $pdo->prepareAndExec($sql, $arg);
    if ($record = $stmt->fetch(PDO::FETCH_ASSOC))
    {
        return $this->_getObjectFromRecord($record);
    }

    // No object found, return empty object
    return new Mapshot(0);
  }


  /**
   * Returns an array of object based on the provided sql
   *
   * @param  string $sql
   * @param  array  $arg
   * @return array
   */
  public function getObjectListFromSql($sql, $arg, $index = null)
  {
      $pdo = PDOMysqlConnection::getInstance();

      $stmt = $pdo->prepareAndExec($sql, $arg);
      $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
      if (is_array($records) && !empty($records)) {
          return $this->_getObjectListFromRecords($records, $index);
      }

      // No object found, return empty array
      return [];
  }
}
