<?php

namespace ModulesGarden\ProxmoxAddon\Core\App
{

    use ModulesGarden\ProxmoxAddon\Core\HandlerError\WhmcsErrorManagerWrapper;

    class AppContext
    {
        protected $debugMode = true;

        public function __construct()
        {
            require_once __DIR__ . DIRECTORY_SEPARATOR . 'ErrorHandler.php';

            register_shutdown_function([$this, 'handleShutdown']);
            set_error_handler([$this, 'handleError'], E_ALL);

            $this->loadDebugState();

            //require app bootstrap
            require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Bootstrap.php';

            if ($this->debugMode)
            {
                spl_autoload_register(array('\ModulesGarden\ProxmoxAddon\Core\App\AppContext', 'loadClassLoader'), true, false);
            }
        }

        public function runApp($callerName = null, $params = [])
        {
            try
            {
                $app    = new Application();
                $result = $app->run($callerName, $params);

                restore_error_handler();
            }
            catch (\Exception $exc)
            {
                restore_error_handler();

                return [
                    'status'  => 'error',
                    'message' => $exc->getMessage()
                ];
            }

            return $result;
        }

        public function handleError($errno, $errstr, $errfile, $errline, $errcontext = null)
        {
            if ($this->debugMode || (!in_array($errno, ErrorHandler::WARNINGS) && !in_array($errno, ErrorHandler::NOTICES)))
            {
                $handler    = new ErrorHandler();
                $errorToken = md5(time());
                $handler->logError($errorToken, $errno, $errstr, $errfile, $errline, $errcontext);
            }

            return true;
        }

        public function handleShutdown()
        {
            $errorInstance = null;
            $errManager    = WhmcsErrorManagerWrapper::getErrorManager();
            if (is_object($errManager) && method_exists($errManager, 'getRunner'))
            {
                $runner = $errManager->getRunner();
                if (is_object($runner) && method_exists($runner, 'getHandlers'))
                {
                    $handlers = $runner->getHandlers();
                    foreach ($handlers as $handler)
                    {
                        $rfHandler = new \ReflectionClass($handler);
                        $method    = $rfHandler->getMethod('getException');
                        $method->setAccessible(true);
                        $error     = $method->invoke($handler);
                        if (is_object($error))
                        {
                            $errorInstance = $error;
                            break;
                        }
                    }
                }
            }

            if ($errorInstance === null)
            {
                $errorInstance = error_get_last();
                if ($errorInstance === null)
                {
                    return;
                }

                $this->handleError($errorInstance['type'], $errorInstance['message'], $errorInstance['file'], $errorInstance['line'], '');

                return;
            }

            $handler    = new ErrorHandler();
            $errorToken = md5(time());
            $handler->logError($errorToken, $errorInstance->getCode(), $errorInstance->getMessage(), $errorInstance->getFile(), $errorInstance->getLine(), $errorInstance->getTrace());
        }

        public function loadDebugState()
        {
            $path = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'debug';
            if (file_exists($path))
            {
                $this->debugMode = true;

                return;
            }

            $this->debugMode = false;
        }

        public static function loadClassLoader($class)
        {
            $rawClass = trim($class, '\\');
            $pos      = strpos($rawClass, 'ModulesGarden\ProxmoxAddon');
            if ($pos === 0)
            {
                if (!class_exists($class) && self::DEPRECATED[$rawClass])
                {
                    echo 'This class no longer exists: ' . $class . '<br>';
                    echo 'Use: ' . self::DEPRECATED[$rawClass];
                    die();
                }
            }
        }
        const DEPRECATED = [
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\BaseMassActionButton'                      => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\ButtonMassAction',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\AddIconModalButton'                        => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\ButtonCreate',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\BaseSubmitButton'                          => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\ButtonSubmitForm',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\BaseButton'                                => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\ButtonBase',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\BaseDatatableModalButton'                  => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\ButtonDatatableShowModal',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\BaseModalDataTableActionButton'            => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\ButtonDataTableModalAction',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\RedirectButton'                            => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\ButtonRedirect',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\BaseModalButton'                           => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\ButtonModal',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\RedirectWithOutTooltipButton'              => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\ButtonRedirect',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\OnOffAjaxSwitch'                           => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\ButtonSwitchAjax',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\CustomActionButton'                        => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\ButtonCustomAction',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\CustomAjaxActionButton'                    => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\ButtonAjaxCustomAction',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\DatatableModalButtonContextLang'           => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\ButtonDatatableModalContextLang',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\DropdownButton'                            => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\ButtonDropdown',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\MassActionButtonContextLang'               => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\ButtonMassActionContextLang',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\Submit'                                    => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\ButtonSubmitForm',
            'ModulesGarden\ProxmoxAddon\Core\HandlerError\WhmcsRegisterLoggin'                            => 'ModulesGarden\ProxmoxAddon\Core\HandlerError\WhmcsLogsHandler',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\ButtonDropdown'                            => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\DropdawnButtonWrappers\ButtonDropdown',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\Dropdowntems\DropdownItemButton'           => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\DropdawnButtonWrappers\ButtonDropdownItem',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\Dropdowntems\DropdownItemCustonAjaxButton' => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\DropdawnButtonWrappers\ButtonDropdownItem',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\Dropdowntems\DropdownItemCustonButton'     => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\DropdawnButtonWrappers\ButtonDropdownItem',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\Dropdowntems\DropdownItemDivider'          => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\DropdawnButtonWrappers\ButtonDropdownItem',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\Dropdowntems\DropdownItemModalButton'      => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\DropdawnButtonWrappers\ButtonDropdownItem',
            'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\Dropdowntems\DropdownItemRedirectButton'   => 'ModulesGarden\ProxmoxAddon\Core\UI\Widget\Buttons\DropdawnButtonWrappers\ButtonDropdownItem',
            'ModulesGarden\ProxmoxAddon\Core\HandlerError\Exceptions\ApiException'                        => 'ModulesGarden\ProxmoxAddon\Core\HandlerError\Exceptions\Exception',
            'ModulesGarden\ProxmoxAddon\Core\HandlerError\Exceptions\ApiWhmcsException'                   => 'ModulesGarden\ProxmoxAddon\Core\HandlerError\Exceptions\Exception',
            'ModulesGarden\ProxmoxAddon\Core\HandlerError\Exceptions\ControllerException'                 => 'ModulesGarden\ProxmoxAddon\Core\HandlerError\Exceptions\Exception',
            'ModulesGarden\ProxmoxAddon\Core\HandlerError\Exceptions\DependencyInjectionException'        => 'ModulesGarden\ProxmoxAddon\Core\HandlerError\Exceptions\Exception',
            'ModulesGarden\ProxmoxAddon\Core\HandlerError\Exceptions\MGModuleException'                   => 'ModulesGarden\ProxmoxAddon\Core\HandlerError\Exceptions\Exception',
            'ModulesGarden\ProxmoxAddon\Core\HandlerError\Exceptions\RegisterException'                   => 'ModulesGarden\ProxmoxAddon\Core\HandlerError\Exceptions\Exception',
            'ModulesGarden\ProxmoxAddon\Core\HandlerError\Exceptions\ServiceLocatorException'             => 'ModulesGarden\ProxmoxAddon\Core\HandlerError\Exceptions\Exception',
            'ModulesGarden\ProxmoxAddon\Core\HandlerError\Exceptions\SmartyException'                     => 'ModulesGarden\ProxmoxAddon\Core\HandlerError\Exceptions\Exception',
        ];
    }

}

namespace
{
}
