<?php

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

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

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

    return self::$_singletonInstance;
  }


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

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


  /**
   * Get PersonalAPI object by key
   *
   * @param  int $id
   * @return PersonalAPI
   */
  public function getObjectByKey($key)
  {
    if (empty($key))
    {
        return new PersonalAPI(0);
    }

    return $this->getObjectFromSql('select * from personal_api where api_key = ? LIMIT 1', [$key]);
  }


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

    return $this->getObjectFromSql('select * from personal_api where user_id = ? LIMIT 1', [$user_id]);
  }


  /**
   * 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 PersonalAPI(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 [];
  }
}
