<?php

namespace Khofmann\Database;

use PDO;
use Khofmann\Config\Config;
use Exception;

class Database extends PDO
{
  private static array $instances = [];

  private function __construct(string $dsn, string $username = null, string $password = null, array $options = null)
  {
    parent::__construct($dsn, $username, $password, $options);
  }

  private function __clone()
  {
    throw new Exception("Cannot clone a singleton.");
  }

  private function __wakeup()
  {
    throw new Exception("Cannot unserialize a singleton.");
  }

  public static function getInstance(): Database
  {
    $cls = static::class;
    if (!isset(self::$instances[$cls])) {
      $dataAccess = Config::getDatabase();
      self::$instances[$cls] = new static(
        "mysql:host={$dataAccess["host"]};dbname={$dataAccess["database"]};charset={$dataAccess["charset"]}",
        $dataAccess["user"],
        $dataAccess["passwd"],
        [
          PDO::ATTR_PERSISTENT => false,
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
          PDO::ATTR_EMULATE_PREPARES   => false,
        ]
      );
    }

    return self::$instances[$cls];
  }
}
