<?php

namespace Ulmus;

use Ulmus\Adapter\AdapterInterface;

use Ulmus\Common\PdoObject;

class ConnectionAdapter
{
    public string $name;

    public array $configuration;

    protected AdapterInterface $adapter;

    protected PdoObject $pdo;

    public function __construct(string $name = "default", array $configuration = [], bool $default = false)
    {
        $this->name = $name;
        
        $this->configuration = $configuration;

        Ulmus::registerAdapter($this, $default);
    }

    public function resolveConfiguration() : void
    {
        $connection = $this->configuration['connections'][$this->name] ?? [];

        if ( false !== ( $adapterName = $connection['adapter'] ?? false ) ) {
            $this->adapter = $this->instanciateAdapter($adapterName);
        }
        else {
            throw new \InvalidArgumentException("Adapter not found within your configuration array.");
        }
        
        $this->adapter->setup($connection);
    }

    public function getConfiguration() : array
    {
        return $this->configuration['connections'][$this->name] ?? [];
    }

    /**
     * Connect the adapter
     * @return self
     */
    public function connect() : self
    {
        $this->pdo = $this->adapter->connect();
        
        return $this;
    }
    
    public function adapter() : AdapterInterface
    {
        return $this->adapter;
    }
    
    public function pdo() : PdoObject
    {
        return $this->pdo ?? $this->pdo = $this->connect()->pdo;
    }

    public function connector() : object
    {
        return $this->pdo();
    }

    /**
     * Instanciate an adapter which interact with the data source
     * @param  string $name An Ulmus adapter or full class name implementing AdapterInterface
     * @return AdapterInterface
     */
    protected function instanciateAdapter($name) : AdapterInterface
    {
        $class = substr($name, 0, 2) === "\\" ? $name : "\\Ulmus\\Adapter\\$name";
        
        return new $class();
    }
}