<?php
require_once(dirname(__DIR__).DIRECTORY_SEPARATOR.'constant.php');
/**
 * PDO Connector for database connexion.
 *
 * @author v.carruesco
 *
 * @category Core
 *
 * @license MIT
 */
class Database {
    public $connections = array();
    public static $instance = null;
    private function __construct() {
        $this->connect();
    }

    /**
     * Methode de recuperation unique de l'instance.
     * @author Valentin CARRUESCO
     * @category Singleton
     * @param <Aucun>
     * @return <pdo> $instance
     */
    public static function instance($baseuid) {
        if (self::$instance === null)
            self::$instance = new self();

        if(!isset(self::$instance->connections[$baseuid]))
            self::$instance->connect($baseuid);

        return self::$instance->connections[$baseuid];
    }

    public static function version($baseUid = 'local'){
         try {
            $db = new self();
            $db->connect();
            return $db->connections[$baseUid]->getAttribute(PDO::ATTR_SERVER_VERSION);
         } catch (Exception $e) {
            return 'Connection à la base impossible : '. $e->getMessage();
        }
    }

    public function connect($baseUid = 'local') {
        try {
            global $databases_credentials;
            $database = $databases_credentials[$baseUid];
            $connector = $database['connector'];
            require_once(__ROOT__.'connector/'.$connector.'.class.php');

            $connectionString = $connector::connection;

            foreach ($database as $key => $value)
                $connectionString = str_replace('{{'.$key.'}}',$value,$connectionString);

            $connectionString = str_replace('{{ROOT}}',__ROOT__,$connectionString);
            $this->connections[$baseUid] = new PDO($connectionString, $database['login'], $database['password'],$connector::pdo_attributes());

            if(method_exists ( $connector , 'beforeTransaction' ))
            $connector::beforeTransaction($this->connections[$baseUid]);
        } catch (Exception $e) {
            echo 'Connection à la base impossible : ', $e->getMessage();
            die();
        }
    }
}
