<?php

namespace FCA\StockApi;

use FCA\StockApi\Exception\ApiException;
use MongoDB\Collection;
use MongoDB\Database;

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

    /**
     * @var $collection Collection
     */
    private $collection = null;

    /**
     * @param Database $database
     * @throws ApiException
     */
    public function setDatabase(Database $database)
    {
        $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($collection)
    {
        if (!($this->db instanceof 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!");
    }

    /**
     * @return Database
     */
    public function getDb()
    {
        return $this->db;
    }

    /**
     * @return Collection
     */
    public function getCollection()
    {
        return $this->collection;
    }
}
