<?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\ViisonPickwareCommon\Subscribers\Api;

use Shopware\Plugins\ViisonCommon\Classes\Subscribers\Base;

class Countries extends Base
{
    /**
     * @see \Shopware\Plugins\ViisonCommon\Classes\Subscribers\Base::getSubscribedEvents()
     */
    public static function getSubscribedEvents()
    {
        return [
            'Shopware_Controllers_Api_Countries::indexAction::after' => [
                'onAfterIndexAction',
                -1000000,
            ],
        ];
    }

    /**
     * Checks the response data for a nested 'data' field and, if found, moves both the
     * nested 'data' and 'total' fields to the top level of the response data. This is
     * a workaround for a bug in the Api\Countries controller, which will be fixed by
     * shopware PR #613.
     *
     * @param \Enlight_Hook_HookArgs $args
     */
    public function onAfterIndexAction(\Enlight_Hook_HookArgs $args)
    {
        // Check status of previous computation
        if ($args->getSubject()->View()->success !== true) {
            return;
        }

        // Fix nesting of data
        $data = $args->getSubject()->View()->data;
        if (isset($data['data'])) {
            $args->getSubject()->View()->data = $data['data'];
            $args->getSubject()->View()->total = $data['total'];
        }
    }
}
