<?php

namespace CCDN\Helpers\Facade;

use CCDN\Helpers\Exception\CCDNRuntimeException;

abstract class FacadeStatic
{

    /**
     * @param  string  $method
     * @param  mixed  $arguments
     * @return mixed
     */
    public static function __callStatic($method, $arguments)
    {
        $instance = static::getFacadeRoot();

        if (!method_exists($instance, $method)) {
            $instance = get_class($instance);
            throw new CCDNRuntimeException("Method {$instance}::{$method}() not exists");
        }

        return $instance->$method(...$arguments);
    }

    /**
     * @return object
     */
    private static function getFacadeRoot()
    {
        $instance = static::getFacadeAccessor();

        if (is_string($instance) && class_exists($instance)) {
            return new $instance;
        }

        if (is_object($instance)) {
            return $instance;
        }

        throw new CCDNRuntimeException('Bad Facade accessor');
    }

    /**
     * Get the class object.
     *
     * @return mixed
     */
    protected static function getFacadeAccessor()
    {
        throw new CCDNRuntimeException('Facade does not implement getFacadeAccessor method.');
    }

}
