<?php


namespace Api\PhpUtils\Mysql;

use Medoo\Medoo;


abstract class DB
{
    private static $instance;

    public static function getInstance(...$args)
    {
        if(!isset(self::$instance)){
            self::$instance=new static(...$args);
        }
        return self::$instance;
    }

    private function __construct($config_db_name, array $options = [])
    {
        try {
            $db_conf = config('mysql', $config_db_name);
            if(!$db_conf){
                throw new \Exception('mysql config not exist');
            }

            ini_set('mysqlnd.net_read_timeout', $db_conf['read_timeout'] ?? 30 );
            $this->db = new Medoo(
                [
                    'database_type' => $db_conf['database_type'] ?? "",
                    'database_name' => $db_conf['name'] ?? "",
                    'charset'       => $db_conf['charset'] ?? "",
                    'port'          => $db_conf[$this->type]['port'] ?? $db_conf['port'] ?? "",
                    'server'        => $db_conf[$this->type]['host'] ?? "",
                    'username'      => $db_conf[$this->type]['username'] ?? "",
                    'password'      => $db_conf[$this->type]['password'] ?? "",
                    'option'        => array_replace([
                        \PDO::ATTR_STRINGIFY_FETCHES    => false,
                        \PDO::ATTR_EMULATE_PREPARES     => false,
                        \PDO::ATTR_CASE                 => \PDO::CASE_NATURAL,
                        \PDO::ATTR_TIMEOUT              => $db_conf['connect_timeout'] ?? 30
                    ], $options)
                ]
            );
        }catch (\Exception $e){
            throw $e;
        }
    }

}