<?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\ViisonPickwareMobile\Classes\ApiRequestCompatibility;

use Shopware\CustomModels\ViisonPickwareMobile\PickProfile\PickProfile;
use Shopware\Models\Order\History;
use Shopware\Plugins\ViisonPickwareCommon\Classes\ApiRequestCompatibility\Layer;

class Orders20181105 extends Layer
{
    /**
     * @inheritdoc
     */
    public function getVersion()
    {
        return '2018-11-05';
    }

    /**
     * Removes any 'pickwarePicking' filter element from the request parameters and adds the ID of the default pick
     * profile instead.
     *
     * pre GET /api/orders
     */
    public function preIndexAction()
    {
        $filter = $this->request->getParam('filter', []);
        $pickwarePickingFilterIndex = -1;
        foreach ($filter as $index => $filterElement) {
            if (is_string($filterElement) && $filterElement === 'pickwarePicking') {
                $pickwarePickingFilterIndex = $index;
                break;
            }
        }
        if ($pickwarePickingFilterIndex > -1) {
            // Remove the filter item and add the ID of the the first pick profile to the request
            unset($filter[$pickwarePickingFilterIndex]);
            $this->request->setParam('filter', $filter);
            $this->addDefaultPickProfileIdToRequest();
        }
    }

    /**
     * Copies the new order fields for prioritized dispatch and payment methods to their respective old fields.
     *
     * post GET /api/orders
     */
    public function postIndexAction()
    {
        $data = $this->view->data;
        if (!is_array($data)) {
            return;
        }

        foreach ($data as &$order) {
            $order['privileged'] = isset($order['prioritizedDispatchMethod']) && $order['prioritizedDispatchMethod'];
            if (is_array($order['payment'])) {
                $order['payment']['privileged'] = isset($order['prioritizedPaymentMethod']) && $order['prioritizedPaymentMethod'];
            }
        }
        unset($order);

        $this->view->data = $data;
    }

    /**
     * Removes any 'pickwarePicking' filter element from the request parameters and adds the ID of the default pick
     * profile instead.
     *
     * pre PUT /api/orders/{id}/lock
     */
    public function prePutLockAction()
    {
        $this->addDefaultPickProfileIdToRequest();
    }

    /**
     * Extracts some of the order data and removes the rest from the response.
     *
     * post PUT /api/orders/{id}/lock
     */
    public function postPutLockAction()
    {
        $data = $this->view->data;
        if (!is_array($data)) {
            return;
        }

        $data['details'] = $data['order']['details'];
        $data['orderStatusId'] = $data['order']['orderStatusId'];
        $data['processingWarehouseId'] = $data['order']['processingWarehouseId'];
        $data['lockedUser'] = $this->getLockedUser($data['order']['id']);
        unset($data['order']);

        $this->view->data = $data;
    }

    /**
     * Adds the ID of the default pick profile as a request parameters.
     *
     * pre PUT /api/orders
     */
    public function preBatchAction()
    {
        $this->addDefaultPickProfileIdToRequest();
    }

    /**
     * @param int $orderId
     * @return array|null
     */
    private function getLockedUser($orderId)
    {
        // Determine the user, who locked the order
        $historyEntry = $this->get('models')->getRepository(History::class)->findOneBy(
            [
                'orderId' => $orderId,
            ],
            [
                'id' => 'DESC',
            ]
        );
        if ($historyEntry) {
            return [
                'userName' => ($historyEntry->getUser()) ? $historyEntry->getUser()->getUserName() : 'unknown_user',
                'name' => ($historyEntry->getUser()) ? $historyEntry->getUser()->getName() : 'Unknown user',
            ];
        }

        return null;
    }

    private function addDefaultPickProfileIdToRequest()
    {
        $pickProfile = $this->get('models')->getRepository(PickProfile::class)->findOneBy([]);
        if ($pickProfile) {
            $this->request->setParam('pickProfileId', $pickProfile->getId());
        }
    }
}
