<?php
/**
 * @package edoobox
 */

namespace Edoobox;

use Edoobox\Helpers\Arr;

final class Plugin {

    private static array $config = ['initialised' => false];
    public static string $bootstrapVersion = "3.4";

    public static function getAdminServices(): array {

        if (conflict_prevents_execution()) {
            return [
                // load translations first!
                Base\Translation::class,
                Pages\Admin::class
            ];
        }

        return [
            // load translations first!
            Base\Translation::class,
            Pages\Admin::class,
            Base\Timezone::class,
            Base\ActionHooks::class,
            Base\Rewrite::class,
            Base\SettingsLinks::class,
            Base\Enqueue::class
        ];
    }

    public static function getFrontendServices(): array {
        return [
            Base\Timezone::class,
            Base\ActionHooks::class,
            Base\Rewrite::class,
            Base\DocumentHead::class,
            Base\BodyTag::class,
            Pages\Frontend::class,
            Base\Enqueue::class
        ];
    }

    public static function get(string $key, $default = null) {
        if ( ! self::$config['initialised']) {
            self::$config = [
                'initialised' => true,
                'plugin_url' => plugin_dir_url(dirname(__FILE__, 1))
            ];
        }
        return Arr::get(self::$config, $key, $default);
    }

    /**
     * Loop through the service classes, initialize them
     * and call the register method on them, if it exists
     *
     * @return void
     */
    public static function registerServices() {
        $services = is_admin() ? self::getAdminServices() : self::getFrontendServices();
        foreach ( $services as $class ) {
            $service = self::instantiate($class);
            if ( method_exists($service, 'register') ) {
                $service->register();
            }
        }
    }

    public static function getBootstrapVersion(): float {
        return (float) self::$bootstrapVersion;
    }

    public static function setBootstrapVersion(string $version = "3.4") {
        self::$bootstrapVersion = $version;
    }

    /**
     * Initialize a given class
     *
     * @param class $class class from the services array
     * @return class instance   new instance of class
     */
    private static function instantiate($class) {
        return new $class;
    }
}