<?php

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

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

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

    return self::$_singletonInstance;
  }


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

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


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

    static $cache = array();
    $key = $user_id;
    if (!isset($cache[$key]))
    {
        $cache[$key] = $this->getObjectFromSql('select * from filter_presets where user_id = ? LIMIT 1', [$user_id]);
    }
    return $cache[$key];
  }


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

    static $cache = array();
    $key = $user_id;
    if (!isset($cache[$key]))
    {
        $cache[$key] = $this->getObjectListFromSql('select * from filter_presets where user_id = ?', [$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 FilterPreset(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 [];
  }
}
