<?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\ViisonShippingCommon\Classes\Subscribers;

use Shopware\Plugins\ViisonCommon\Classes\Subscribers\Base as ViisonCommonSubscriberBase;
use Shopware\Plugins\ViisonCommon\Classes\Util\Util as ViisonCommonUtil;
use Enlight_Controller_Action;

/**
 * Abstract Class Index
 *
 * This class is used to register the onPostDispatchSecureIndex subscriber
 */
abstract class Index extends ViisonCommonSubscriberBase
{

    /** @var string The icon name, by default this icon name is used in all Adapter */
    protected $iconName = 'plugin.png';
    /**
     * @deprecated This is obsolete. It does not work in composer-installed Shopware.
     * @var string The Shopware plugin folder Path (looking from the root path)
     */
    protected $shopwarePluginsFolder = '/engine/Shopware/Plugins/';

    /**
     * All extended templates that the adapter extends
     *
     * @param array $view
     */
    abstract protected function extendTemplates($view);

    /**
     * Add the path to the plugin's icon PNG to the view parameters
     *
     * @param $view
     * @param $plugin
     * @param $args
     */
    abstract protected function setPluginIconPath($view, $plugin, $args);

    /**
     * @Override from ViisonCommon
     */
    public static function getSubscribedEvents()
    {
        return array(
            'Enlight_Controller_Action_PostDispatchSecure_Backend_Index' => 'onPostDispatchSecureIndex'
        );
    }

    /**
     * Adds custom extensions to the loaded sub application, which cannot be loaded using
     * ViisonCommon's sub application loader.
     *
     * @param \Enlight_Event_EventArgs $args
     */
    public function onPostDispatchSecureIndex(\Enlight_Event_EventArgs $args)
    {
        if ($args->getRequest()->getActionName() === 'index') {
            $view = $args->getSubject()->View();
            $plugin = ViisonCommonUtil::getPlugin($this->getPluginBootstrap()->getName());

            $this->setPluginIconPath($view, $plugin, $args);
            $this->extendTemplates($view);
        }
    }

    /**
     * Returns the plugin icon path used for the Menu entry
     *
     * @param \Enlight_Event_EventArgs $args
     * @param $plugin
     * @return string
     */
    public function getPluginIconPath(\Enlight_Event_EventArgs $args, $plugin)
    {
        // Implement analogously to Shopware\Bundle\PluginInstallerBundle\Service\PluginLocalService::getIconOfPlugin.
        $container = $this->getContainer();
        if ($container->hasParameter('shopware.app.rootDir')) {
            $rootDir = $container->getParameter('shopware.app.rootDir');
        } else {
            // Shopware < 5.4
            // Note: In a composer setup (not supported below Shopware 5.4), this would be inside the vendor directory.
            $rootDir = $container->getParameter('kernel.root_dir');
        }
        $absolutePluginDirName = $container->get('shopware_plugininstaller.plugin_manager')->getPluginPath(
            $plugin->getName()
        );
        $absoluteIconFileName = $absolutePluginDirName . '/' . $this->iconName;
        $relativePath = str_replace($rootDir, '', $absoluteIconFileName);
        if (!file_exists($absoluteIconFileName)) {
            // This should never happen in a properly configured Shopware installation.
            // However, we handle this case, because invalid URLs may trigger ill behavior in the backend.
            // For example, should the URL point to a non-existent file, it may be handled by Shopware's routing and
            // authorization logic.
            // If a request to that file results in a 401 status code, the backend will decide to logout the active
            // user.
            // Return an empty gif in this case.
            return 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
        }

        return $args->getSubject()->Request()->getBasePath() . '/' . ltrim($relativePath, '/');
    }
}
