<?php

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

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

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

    return self::$_singletonInstance;
  }


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

    static $cache = array();
    $key = $id;
    if (!isset($cache[$key]))
    {
        $cache[$key] = $this->getObjectFromSql('select *, UNIX_TIMESTAMP(last_update) AS last_update_ts from user_preferences where id = ? LIMIT 1', [$id]);
    }
    return $cache[$key];
  }


  /**
   * Get user settings object by user id
   *
   * @param  int $user_id
   * @return UserSettings
   */
  public function getObjectByUserId($user_id)
  {
    if (!isInt($user_id))
    {
        return new UserSettings(0);
    }

    static $cache = array();
    $key = $user_id;
    if (!isset($cache[$key]))
    {
        $cache[$key] = $this->getObjectFromSql('select *, UNIX_TIMESTAMP(last_update) AS last_update_ts from user_preferences where user_id = ? LIMIT 1', [$user_id]);
    }
    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 UserSettings(0);
  }
}
