<?php
/**
 * Created by PhpStorm.
 * Damian Banaszkiewicz <dbanaszkiewicz@unicorn.net.pl>
 * 23.08.18 08:40
 */

namespace FCA\StockApi;

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

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

    /**
     * @var $collection Collection
     */
    public static $collection = null;

    /**
     * @param Database $database
     * @throws ApiException
     */
    public static function setDatabase(Database $database)
    {
        Api::$db = $database;

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

    /**
     * @param $collection
     * @throws ApiException
     */
    public static function setCollection($collection)
    {
        if (!(Api::$db instanceof Database)) {
            throw new ApiException("Database connection is missing!");
        }

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

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

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