<?php
declare(strict_types=1);

namespace FCA\StockApi;

use FCA\StockApi\Exception\ApiException;

class Api
{
    /**
     * @var \MongoDB\Database|null $db
     */
    private $db = null;

    /**
     * @var \MongoDB\Collection|null $collection
     */
    private $collection = null;

    /**
     * @param \MongoDB\Database $database
     * @throws ApiException
     */
    public function setDatabase(\MongoDB\Database $database): void
    {
        $this->db = $database;

        try {
            $this->db->command(['connectionStatus' => 1]);
        } catch (\Exception $e) {
            throw new ApiException('Cannot connect to database!');
        }
    }

    /**
     * @param $collection
     * @throws ApiException
     */
    public function setCollection(string $collection): void
    {
        if (!($this->db instanceof \MongoDB\Database)) {
            throw new ApiException('Database connection is missing!');
        }

        try {
            $collections = $this->db->listCollections();

            foreach ($collections as $c) {
                if ($c->getName() === $collection) {
                    $this->collection = $this->db->selectCollection($collection);
                    return;
                }
            }
        } catch (\Exception $e) {
            throw new ApiException('Cannot connect to database!');
        }

        throw new ApiException('Cannot find collection!');
    }

    public function getDb(): \MongoDB\Database
    {
        return $this->db;
    }

    public function getCollection(): \MongoDB\Collection
    {
        return $this->collection;
    }
}
