<?php

namespace idoit\Module\Qrcode\Controller;

use BaconQrCode\Renderer\Image\SvgImageBackEnd;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;
use idoit\Module\Qrcode\Component\QrCode;
use isys_application;
use Picqer\Barcode\BarcodeGenerator;
use Picqer\Barcode\BarcodeGeneratorSVG;
use SplFileInfo;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Throwable;

/**
 * QRCode relevant image controller.
 *
 * @package   Modules
 * @copyright synetics GmbH
 * @license   http://www.i-doit.com/license
 */
class ImageController
{
    /**
     * @param Request $request
     * @param int     $objectId
     *
     * @return Response
     */
    public function getObjectQrCode(Request $request, int $objectId): Response
    {
        try {
            $data = (new QrCode())->getData($objectId);

            if (empty($data)) {
                return $this->dummyIcon();
            }

            $renderer = new ImageRenderer(new RendererStyle(200, 0), new SvgImageBackEnd());
            $imageData = (new Writer($renderer))->writeString($data['url']);

            return (new Response($imageData, Response::HTTP_OK, ['Content-Type' => 'image/svg+xml']));
        } catch (Throwable $e) {
            return $this->errorIcon();
        }
    }

    /**
     * @param Request $request
     * @param int     $objectId
     *
     * @return Response
     */
    public function getObjectBarcode(Request $request, int $objectId): Response
    {
        try {
            $data = (new QrCode())->getData($objectId);

            if (empty($data)) {
                return $this->dummyIcon();
            }

            $imageData = (new BarcodeGeneratorSVG())->getBarcode($data['sysid'], BarcodeGenerator::TYPE_CODE_39, 2, 40);

            return (new Response($imageData, Response::HTTP_OK, ['Content-Type' => 'image/svg+xml']));
        } catch (Throwable $e) {
            return $this->errorIcon();
        }
    }

    /**
     * Use this if a image could not be loaded, due to mis-configuration.
     *
     * @return Response
     */
    private function dummyIcon(): Response
    {
        $dummyIcon = new SplFileInfo(isys_application::instance()->app_path . 'images/axialis/basic/button-help.svg');

        return new BinaryFileResponse($dummyIcon, Response::HTTP_OK, ['Content-Type' => 'image/svg+xml']);
    }

    /**
     * Use this if an error occured.
     * The error itself should be logged and checked by the customer / support.
     *
     * @return Response
     */
    private function errorIcon(): Response
    {
        $errorIcon = new SplFileInfo(isys_application::instance()->app_path . 'images/axialis/basic/button-info-red.svg');

        return new BinaryFileResponse($errorIcon, Response::HTTP_OK, ['Content-Type' => 'image/svg+xml']);
    }
}
