<?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\Subscriber;

use Shopware\Plugins\ViisonCommon\Classes\Subscribers\Base;
use Shopware\Plugins\ViisonCommon\Components\PluginConfigImporterService;
use Shopware\Plugins\ViisonShippingCommon\Classes\PluginInfo;
use Shopware\Plugins\ViisonShippingCommon\Components\ShippingPluginConfigReaderService;

class ConfigImporterSubscriber extends Base
{
    /**
     * @var PluginInfo
     */
    private $pluginInfo;

    /**
     * @param \Shopware_Components_Plugin_Bootstrap $pluginBootstrap
     * @param PluginInfo $pluginInfo
     */
    public function __construct(\Shopware_Components_Plugin_Bootstrap $pluginBootstrap, PluginInfo $pluginInfo)
    {
        parent::__construct($pluginBootstrap);

        $this->pluginInfo = $pluginInfo;
    }

    /**
     * @inheritdoc
     */
    public static function getSubscribedEvents()
    {
        return [
            PluginConfigImporterService::NOTIFY_UNTIL_ALLOW_STANDARD_IMPORT_EVENT => 'onAllowStandardImport',
        ];
    }

    /**
     * Imports config of a shipping adapter and returns its pluginInfo.
     *
     * @param \Enlight_Event_EventArgs $args
     * @return null|PluginInfo
     */
    public function onAllowStandardImport(\Enlight_Event_EventArgs $args)
    {
        $requestedPluginName = $args->get('plugin')->getName();
        if ($requestedPluginName !== $this->pluginInfo->getPluginName()) {
            return null;
        }

        $this->get('viison_shipping_common.plugin_config_importer')->importShippingConfigFormFile(
            $args->get('configPath'),
            $args->get('shop'),
            $this->pluginInfo
        );

        // Return true to prevent the default importer from trying to import the config
        return true;
    }
}
