<?php

declare(strict_types=1);

namespace vonRotenberg\RealEstateListingBundle\Controller\FrontendModule;

use Contao\Config;
use vonRotenberg\RealEstateListingBundle\Model\ManagedPropertyModel;
use Contao\ArrayUtil;
use Contao\Controller;
use Contao\CoreBundle\Controller\FrontendModule\AbstractFrontendModuleController;
use Contao\CoreBundle\DependencyInjection\Attribute\AsFrontendModule;
use Contao\CoreBundle\Exception\ResponseException;
use Contao\CoreBundle\Image\Studio\Figure;
use Contao\CoreBundle\Image\Studio\FigureBuilder;
use Contao\CoreBundle\Twig\FragmentTemplate;
use Contao\Date;
use Contao\File;
use Contao\FilesModel;
use Contao\FrontendTemplate;
use Contao\Input;
use Contao\ModuleModel;
use Contao\PageModel;
use Contao\StringUtil;
use Contao\System;
use Contao\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Translation\TranslatorInterface;
use vonRotenberg\RealEstateListingBundle\Model\RealEstateAssetsModel;

#[AsFrontendModule(category: 'vr_real_estate')]
class ManagedPropertyReaderController extends AbstractFrontendModuleController
{
    public const TYPE = 'managed_property_reader';
    /**
     * @var RealEstateAssetsModel|null
     */
    protected $asset;

    /**
     * @var TranslatorInterface
     */
    protected $translator;

    protected function getResponse(FragmentTemplate $template, ModuleModel $model, Request $request): Response
    {
        $this->translator = System::getContainer()->get('translator');
        Controller::loadLanguageFile(ManagedPropertyModel::getTable());

        $jumpTo = PageModel::findByPk($model->jumpTo);

        // Set the item from the auto_item parameter
        if (!isset($_GET['items']) && Input::get('auto_item'))
        {
            Input::setGet('items', Input::get('auto_item'));
        }

        $this->asset = ManagedPropertyModel::findPublishedByIdOrAlias(Input::get('items'));

        if ($this->asset === null)
        {
            return new Response();
        }

        $figureBuilder = System::getContainer()
            ->get('contao.image.studio')
            ->createFigureBuilder()
            ->setSize($model->imgSize)
            ->enableLightbox(true);
//      ->setLightboxGroupIdentifier('lb' . $model->id);

        $arrItem = array_merge($this->asset->row(), [
            'features'          => StringUtil::deserialize($this->asset->features,true),
            'availableFrom'     => ($this->asset->availability == 'immediately' ? $this->translator->trans('REF.re_availability.immediately', [], 'contao_default') : Date::parse(Date::getNumericDateFormat(), $this->asset->availableFrom)),
            'deadline'          => ($this->asset->stop > 0 ? Date::parse(Date::getNumericDateFormat(), $this->asset->stop) : ''),
            'teaserFigure'      => $this->getImageFigures($this->asset->gallerySRC, $figureBuilder, $this->asset->orderSRC, 1),
            'galleryFigures'    => $this->getImageFigures($this->asset->gallerySRC, $figureBuilder, $this->asset->orderSRC, 0, 0),
            'floorPlansFigures' => $this->getImageFigures($this->asset->floorPlansSRC, $figureBuilder, $this->asset->floorPlansOrderSRC),
            'listUrl'           => $jumpTo !== null ? $jumpTo->getFrontendUrl() : null,
            'pdfUrl'            => $request->getBaseUrl() . $request->getPathInfo() . '?pdf',
            'qrUrl'             => $request->getUriForPath($request->getPathInfo()),
            'map'               => $this->asset->mapIframe ?? ''
        ]);

        $template->item = $arrItem;

        return $template->getResponse();
    }

    /**
     * @param string|array  $strUuids
     * @param FigureBuilder $figureBuilder
     * @param string|array  $strOrder
     *
     * @return array|Figure
     * @throws \Exception
     */
    public function getImageFigures($strUuids, $figureBuilder, $strOrder = null, int $intLimit = 0, int $intOffset = 0)
    {
        $arrImageFigures = [];

        if (($imageFiles = FilesModel::findMultipleByUuids(StringUtil::deserialize($strUuids))) !== null)
        {
            $images = array();
            while ($imageFiles->next())
            {
                // Continue if the files has been processed or does not exist
                if (isset($images[$imageFiles->path]) || !file_exists(System::getContainer()->getParameter('kernel.project_dir') . '/' . $imageFiles->path))
                {
                    continue;
                }

                // Single files
                if ($imageFiles->type == 'file')
                {
                    $objFile = new File($imageFiles->path);

                    if (!$objFile->isImage)
                    {
                        continue;
                    }

                    // Add the image
                    $images[$imageFiles->path] = $imageFiles->current();
                } // Folders
                else
                {
                    $objSubfiles = FilesModel::findByPid($imageFiles->uuid, array('order' => 'name'));

                    if ($objSubfiles === null)
                    {
                        continue;
                    }

                    while ($objSubfiles->next())
                    {
                        // Skip subfolders
                        if ($objSubfiles->type == 'folder')
                        {
                            continue;
                        }

                        $objFile = new File($objSubfiles->path);

                        if (!$objFile->isImage)
                        {
                            continue;
                        }

                        // Add the image
                        $images[$objSubfiles->path] = $objSubfiles->current();
                    }
                }
            }

            if ($strOrder !== null)
            {
                $images = ArrayUtil::sortByOrderField($images, $strOrder);
            }
            $images = array_values($images);

            // Offset images
            if ($intOffset > 0)
            {
                $images = \array_slice($images, ($intOffset < count($images) ? $intOffset : count($images)));
            }

            // Limit number of images
            if ($intLimit > 0)
            {
                $images = \array_slice($images, 0, $intLimit);
            }

            // Build figures of images
            foreach ($images as $image)
            {
                $figure = $figureBuilder
                    ->fromFilesModel($image)
                    ->build();

                $arrImageFigures[] = $figure;
            }

        }
        return count ($arrImageFigures) === 1 && $intLimit === 1 ? array_shift($arrImageFigures) : $arrImageFigures;
    }
}