<?php

namespace vonRotenberg\RealEstateListingBundle\Controller\FrontendModule;

use vonRotenberg\RealEstateListingBundle\Model\RealEstateAssetsModel;
use Contao\ArrayUtil;
use Contao\CoreBundle\Controller\FrontendModule\AbstractFrontendModuleController;
use Contao\CoreBundle\Image\Studio\Figure;
use Contao\CoreBundle\Image\Studio\FigureBuilder;
use Contao\File;
use Contao\FilesModel;
use Contao\Model\Collection;
use Contao\StringUtil;
use Contao\System;

abstract class RealEstateAssetsModuleController extends AbstractFrontendModuleController
{

  /**
   * @param $arrCategories
   *
   * @return RealEstateAssetsModel|RealEstateAssetsModel[]|Collection|null
   */
  public function getRealEstateAssets($arrCategories, array $arrOptions=array())
  {
    if (empty($arrCategories) || !\is_array($arrCategories))
    {
      return null;
    }

    return RealEstateAssetsModel::findPublishedByParent($arrCategories, 0,0,$arrOptions);
  }

  /**
   * @param $arrCategories
   *
   * @return integer
   */
  public function countRealEstateAssets($arrCategories, array $arrOptions=array())
  {
    return RealEstateAssetsModel::countPublishedByParent($arrCategories,$arrOptions);
  }

  /**
   * @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;
  }

  public function getImageDataUrl($path)
  {
    $type = pathinfo($path, PATHINFO_EXTENSION);
    $data = file_get_contents($path);
    return 'data:image/' . $type . ';base64,' . base64_encode($data);
  }
}
