<?php

namespace ThurData\Servers\KerioEmail\Core\App;

use ThurData\Servers\KerioEmail\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('\ThurData\Servers\KerioEmail\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)
        {

            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $exc,
                'Debug Application',
                $result
            );
    
            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());
        if ($errorToken)
        {
            echo '<input type="hidden" id="mg-sh-h-492318-64534" value="' . $errorToken . '" mg-sh-h-492318-64534-end >';
        }
    }

    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, 'ThurData\Servers\KerioEmail');
        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 = [
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\BaseMassActionButton' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\ButtonMassAction',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\AddIconModalButton' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\ButtonCreate',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\BaseSubmitButton' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\ButtonSubmitForm',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\BaseButton' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\ButtonBase',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\BaseDatatableModalButton' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\ButtonDatatableShowModal',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\BaseModalDataTableActionButton' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\ButtonDataTableModalAction',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\RedirectButton' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\ButtonRedirect',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\BaseModalButton' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\ButtonModal',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\RedirectWithOutTooltipButton' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\ButtonRedirect',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\OnOffAjaxSwitch' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\ButtonSwitchAjax',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\CustomActionButton' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\ButtonCustomAction',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\CustomAjaxActionButton' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\ButtonAjaxCustomAction',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\DatatableModalButtonContextLang' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\ButtonDatatableModalContextLang',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\DropdownButton' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\ButtonDropdown',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\MassActionButtonContextLang' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\ButtonMassActionContextLang',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\Submit' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\ButtonSubmitForm',
        'ThurData\Servers\KerioEmail\Core\HandlerError\WhmcsRegisterLoggin' => 'ThurData\Servers\KerioEmail\Core\HandlerError\WhmcsLogsHandler',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\ButtonDropdown' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\DropdawnButtonWrappers\ButtonDropdown',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\Dropdowntems\DropdownItemButton' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\DropdawnButtonWrappers\ButtonDropdownItem',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\Dropdowntems\DropdownItemCustonAjaxButton' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\DropdawnButtonWrappers\ButtonDropdownItem',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\Dropdowntems\DropdownItemCustonButton' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\DropdawnButtonWrappers\ButtonDropdownItem',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\Dropdowntems\DropdownItemDivider' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\DropdawnButtonWrappers\ButtonDropdownItem',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\Dropdowntems\DropdownItemModalButton' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\DropdawnButtonWrappers\ButtonDropdownItem',
        'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\Dropdowntems\DropdownItemRedirectButton' => 'ThurData\Servers\KerioEmail\Core\UI\Widget\Buttons\DropdawnButtonWrappers\ButtonDropdownItem',
        'ThurData\Servers\KerioEmail\Core\HandlerError\Exceptions\ApiException' => 'ThurData\Servers\KerioEmail\Core\HandlerError\Exceptions\Exception',
        'ThurData\Servers\KerioEmail\Core\HandlerError\Exceptions\ApiWhmcsException' => 'ThurData\Servers\KerioEmail\Core\HandlerError\Exceptions\Exception',
        'ThurData\Servers\KerioEmail\Core\HandlerError\Exceptions\ControllerException' => 'ThurData\Servers\KerioEmail\Core\HandlerError\Exceptions\Exception',
        'ThurData\Servers\KerioEmail\Core\HandlerError\Exceptions\DependencyInjectionException' => 'ThurData\Servers\KerioEmail\Core\HandlerError\Exceptions\Exception',
        'ThurData\Servers\KerioEmail\Core\HandlerError\Exceptions\MGModuleException' => 'ThurData\Servers\KerioEmail\Core\HandlerError\Exceptions\Exception',
        'ThurData\Servers\KerioEmail\Core\HandlerError\Exceptions\RegisterException' => 'ThurData\Servers\KerioEmail\Core\HandlerError\Exceptions\Exception',
        'ThurData\Servers\KerioEmail\Core\HandlerError\Exceptions\ServiceLocatorException' => 'ThurData\Servers\KerioEmail\Core\HandlerError\Exceptions\Exception',
        'ThurData\Servers\KerioEmail\Core\HandlerError\Exceptions\SmartyException' => 'ThurData\Servers\KerioEmail\Core\HandlerError\Exceptions\Exception',
    ];
}
