<?php
  class CADatabaseRepository extends ModelRepository
  {
    private static $_singletonInstance = null;

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

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

      return self::$_singletonInstance;
    }


    /**
     * Get object by id
     *
     * @param  string $callsign (Callsign of the station)
     * @return CADatabase
     */
    public function getObjectByCallsign($callsign = null)
    {
        if (is_null($callsign) || empty($callsign))
        {
            return new CADatabase(null);
        }

        $sql = 'SELECT * FROM ca_license WHERE call_sign = ? LIMIT 1';

        return $this->getObjectFromSql($sql, [$callsign]);
    }

    /**
     * Get object list by query string
     *
     * @param  int   $q
     * @param  int   $limit
     * @param  int   $offset
     * @return array
     */
    public function getObjectListByQueryString($callsign, $limit=50, $offset=0)
    {
      $sql =
        'SELECT *
          FROM ca_license
          WHERE call_sign ILIKE ?
          LIMIT ? OFFSET ?';

      $pdo = PDOConnection::getInstance();
      $stmt = $pdo->prepare($sql);
    	$stmt->bindValue(1, "$callsign%");
      $stmt->bindValue(2, $limit);
      $stmt->bindValue(3, $offset);
      $stmt->execute();

      $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
      if (is_array($records) && !empty($records)) {
          return $this->_getObjectListFromRecords($records);
      }

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

    /**
     * Get number of objects in the object list by query string
     *
     * @param  int   $callsign
     * @return array
     */
    public function getNumberOfStationsByQueryString($callsign)
    {
      $sql =
        'SELECT COUNT(*)
          FROM ca_license
          WHERE call_sign ILIKE ?';

      $pdo = PDOConnection::getInstance();
      $stmt = $pdo->prepare($sql);
      $stmt->bindValue(1, "$callsign%");
      $stmt->execute();

      return $stmt->fetchColumn();
    }
  }
?>
