<?php

defined('APP_BOOTSTRAPPED') or exit('No direct access.');

class GameApi
{
    private static $config = array();
    private static $instances = array();

    public static function init(array $config)
    {
        self::$config = $config;
        self::$instances = array();
    }

    public static function adapter($apiName)
    {
        $apiName = strtolower(trim((string) $apiName));

        if (!in_array($apiName, array('sgx', 'nexus'), true)) {
            throw new GameApiException(
                'API provider tidak dikenal: ' . $apiName,
                422
            );
        }

        if (isset(self::$instances[$apiName])) {
            return self::$instances[$apiName];
        }

        if (
            !isset(self::$config[$apiName]) ||
            !is_array(self::$config[$apiName])
        ) {
            throw new GameApiException(
                'Konfigurasi API ' . strtoupper($apiName) .
                ' tidak tersedia.',
                500
            );
        }

        if ($apiName === 'sgx') {
            self::$instances[$apiName] =
                new SgxGameApiAdapter(self::$config['sgx']);
        } else {
            self::$instances[$apiName] =
                new NexusGameApiAdapter(self::$config['nexus']);
        }

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

    public static function sgx()
    {
        return self::adapter('sgx');
    }

    public static function nexus()
    {
        return self::adapter('nexus');
    }
}
