<?php

namespace AuthStack\Driver\Connection;

use function Buckhill\config;
use AuthStack\Driver\Errors\ConnectionError;
use AuthStack\Driver\Connection\Model\Driver;
use AuthStack\Driver\Driver\AuthDriverInterface;
use AuthStack\Driver\Connection\Model\Connection;
use AuthStack\Driver\Errors\NoSuchConnectionError;

class Manager
{
    public static function initialize($connection_id)
    {
        $connection = Connection::findOrFail($connection_id);

        return static::load($connection);
    }


    /**
     * @param array $driver
     *
     * @return Driver
     */
    public static function install(array $driver)
    {
        return Driver::install($driver);
    }


    /**
     * @param Connection $connection
     *
     * @return AuthDriverInterface
     * @throws ConnectionError
     * @throws NoSuchConnectionError
     */
    protected static function load(Connection $connection)
    {
        /** @var  $blueprint AuthDriverInterface */
        $blueprint = $connection->getDriverClass();

        if(!class_exists($blueprint, true))
        {
            throw new NoSuchConnectionError(sprintf("No such class available: %s. Unable to establish connection.", $blueprint));
        }

        // Create the section for config() function. We'll hash the integer id so we get a unique section name (that's not decimal numeric)
        $section = sha1($connection->id);

        // Set the section and value
        config()->set($section, $connection->getConnectionConfig());

        // Initialize the driver
        $driver = $blueprint::initialize($section, $connection->id);

        if($driver->connect() === false)
        {
            throw new ConnectionError($driver->lastError());
        }

        return $driver;
    }
}