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

/**
 * Because Shopware doesn't allow that Controllers use the new PSR-4 namespace standard
 * we need to require the class, because of Enlight_Class::Instance
 *
 * Note: every Adapter should include their controller path
 */
require_once(__DIR__ . '/../../Controllers/Backend/ViisonShippingCommonOrder.php');

abstract class ViisonShippingCommonOrder extends Base
{
    /**
     * @inheritdoc
     */
    public static function getSubscribedEvents()
    {
        return array(
            'Shopware_Controllers_Backend_ViisonShippingCommonOrder_GetMergedLabelsAction' => 'onFilterGetMergedDocumentsAction'
        );
    }

    abstract protected function createOrderController(\Enlight_Event_EventArgs $args);

    /**
     * Adds Adapter label PDFs to the pdf list passed by the filter event.
     *
     * @param \Enlight_Event_EventArgs $args
     * @return array
     */
    public function onFilterGetMergedDocumentsAction(\Enlight_Event_EventArgs $args)
    {
        $controller = $this->createOrderController($args);

        return array_merge($args->getReturn(), $controller->getLabelPDFs($this->getDocumentIdentifier($args)));
    }

    /**
     * @deprecated
     * Adds Adapter export document PDFs to the pdf list passed by the filter event.
     * By Default it is not included, so The Adapter who wants to listen to this event needs to include it in getSubscribedEvents()
     *
     * @param \Enlight_Event_EventArgs $args
     * @return array
     */
    public function onFilterGetMergedExportDocumentsAction(\Enlight_Event_EventArgs $args)
    {
        $controller = $this->createOrderController($args);

        return array_merge($args->getReturn(), $controller->getExportDocumentPDFs($this->getDocumentIdentifier($args)));
    }

    /**
     * Get document Identifier from Request
     *
     * @param $args
     * @return mixed
     */
    protected function getDocumentIdentifier($args)
    {
        $documentIdentifiers = json_decode($args->getSubject()->Request()->getParam('documentIdentifiers'));

        /**
         * @depreceted
         * Use tracking code as fallback for backward compatibility
         */
        $documentIdentifiers = $documentIdentifiers ?: json_decode(
            $args->getSubject()->Request()->getParam('trackingCodes', null)
        );

        return $documentIdentifiers;
    }
}
