<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonCommon\Subscribers\Controller\Frontend;

use ArrayObject;
use Enlight_Hook_HookArgs;
use Shopware\Plugins\ViisonCommon\Classes\Subscribers\AbstractBaseSubscriber;
use Shopware\Plugins\ViisonCommon\Components\ExceptionTranslation\ExceptionTranslator;

class FrontendErrorControllerSubscriber extends AbstractBaseSubscriber
{
    /**
     * @inheritdoc
     */
    public static function getSubscribedEvents()
    {
        return [
            'Shopware_Controllers_Backend_Error::genericErrorAction::after' => 'onAfterGenericErrorAction',
        ];
    }

    /**
     * If an exception is thrown in a backend this subscriber tries to show a localized message of the exception.
     *
     * @param Enlight_Hook_HookArgs $args
     */
    public function onAfterGenericErrorAction(\Enlight_Hook_HookArgs $args)
    {
        /** @var \Shopware_Controllers_Frontend_Error $subject */
        $subject = $args->getSubject();

        if (!$subject->Front()->getParam('showException') && $subject->Request()->getModuleName() !== 'backend') {
            return;
        }
        /** @var ArrayObject $error */
        $error = $subject->Request()->getParam('error_handler');
        /** @var \Exception $exception */
        $exception = $error->exception;

        /** @var ExceptionTranslator $exceptionTranslator */
        $exceptionTranslator = $this->get('viison_common.exception_translator');

        $subject->View()->assign('message', $exceptionTranslator->translate($exception));
    }
}
