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

use Shopware\Components\Api\Exception as ApiException;
use Shopware\Models\Order\Document\Document as OrderDocument;
use Shopware\Plugins\ViisonCommon\Classes\Exceptions\FileSystemExceptions\FileNotReadableException;
use Shopware\Plugins\ViisonCommon\Classes\Util\Document as DocumentUtil;

/**
 * This trait can be used in REST API controllers to provide responses containing order documents.
 */
trait OrderDocumentResponding
{
    private function makeOrderDocumentResponseData(OrderDocument $document, $includeFileData = true)
    {
        $responseData = [
            'id' => $document->getId(),
            'typeId' => $document->getType()->getId(),
            'number' => $document->getDocumentId(),
            // Order documents always use a DIN-A4 page size
            'pageSize' => 'DIN-A4',
        ];

        if ($includeFileData) {
            // Try adding the base64 encoded document data to the response
            $fileName = DocumentUtil::getDocumentFileName($document);
            /** @var FileStorage $documentFileStorage */
            $documentFileStorage = $this->get('viison_common.document_file_storage_service');
            try {
                $fileData = $documentFileStorage->readFileContents($fileName);
                $responseData['fileData'] = base64_encode($fileData);
            } catch (FileNotReadableException $e) {
                throw new ApiException\NotFoundException(
                    sprintf('The file of order document with ID %d does not exist.', $document->getId()),
                    0,
                    $e
                );
            }
        }

        return $responseData;
    }
}
