<?php

/**
 * Pageimage for Contao
 *
 * Copyright (c) 2015 Benjamin Roth
 *
 * @license LGPL-3.0+
 */

namespace eSM_pageimage;

 
class Pageimage extends \Frontend
{

    public static function getImages()
    {
        global $objPage;
        $arrImages = array();

        // Image settings
        $sb_imageUrl = deserialize($objPage->sb_imageUrl,true);
        $sb_imageOrder = deserialize($objPage->sb_imageOrder,true);
        $sb_imageSize = $objPage->sb_imageSize;

        // Inherit images if current page has none
        if ((!count($sb_imageUrl) || (count($sb_imageUrl) == 1 && !$sb_imageUrl[0])) && !$objPage->sb_imageIgnore)
        {
            $pid = $objPage->id;
            // Inherit settings
            do
            {
                $objParentPage = \Database::getInstance()->prepare("SELECT * FROM tl_page WHERE id=?")
                    ->limit(1)
                    ->execute($pid);
                if ($objParentPage->numRows < 1)
                {
                    break;
                }

                $pid = $objParentPage->pid;
                $type = $objParentPage->type;

                $arrParentImageUrl = deserialize($objParentPage->sb_imageUrl);

                if ((!is_array($sb_imageUrl) || !count($sb_imageUrl) || !$sb_imageUrl[0]) && (is_array($arrParentImageUrl) && count($arrParentImageUrl) && $arrParentImageUrl[0]))
                {

                    $sb_imageUrl = deserialize($objParentPage->sb_imageUrl,true);
                    $sb_imageSize = $objParentPage->sb_imageSize;
                    $sb_imageOrder = deserialize($objParentPage->sb_imageOrder,true);
                    break;
                }
            }
            while ($pid > 0 && $type != 'root');
        }

        // Order images
        if (count($sb_imageOrder) && count($sb_imageUrl) && $sb_imageUrl[0])
        {
            $tmp = $sb_imageOrder;

            if (!empty($tmp) && is_array($tmp))
            {
                // Remove all values
                $arrOrder = array_map(function(){}, array_flip($tmp));

                // Move the matching elements to their position in $arrOrder
                foreach ($sb_imageUrl as $k=>$v)
                {
                    if (array_key_exists($v, $arrOrder))
                    {
                        $arrOrder[$v] = $v;
                        unset($sb_imageUrl[$k]);
                    }
                }

                // Append the left-over images at the end
                if (!empty($sb_imageUrl))
                {
                    $arrOrder = array_merge($arrOrder, array_values($sb_imageUrl));
                }

                // Remove empty (unreplaced) entries
                $sb_imageUrl = array_values(array_filter($arrOrder));
                unset($arrOrder);
            }
        }

        if (count($sb_imageUrl) && $sb_imageUrl[0])
        {

            // Get all images
            $multiSRC = array_values($sb_imageUrl);
            $objFiles = \FilesModel::findMultipleByIds($multiSRC);

            while ($objFiles->next()) {
                // Continue if the files has been processed or does not exist
                if (isset($arrImages[$objFiles->path]) || !file_exists(TL_ROOT.'/'.$objFiles->path)) {
                    continue;
                }

                // Single files
                $objFile = new \File($objFiles->path, true);

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

                $arrMeta = static::getMetaData($objFiles->meta, $objPage->language);

                if (empty($arrMeta)) {
                    if ($objPage->rootFallbackLanguage !== null) {
                        $arrMeta = static::getMetaData($objFiles->meta, $objPage->rootFallbackLanguage);
                    }
                }

                // Use the file name as title if none is given
                if ($arrMeta['title'] == '') {
                    $arrMeta['title'] = specialchars($objFile->basename);
                }

                // Add the image
                $arrImages[$objFiles->path] = array
                (
                    'id' => $objFiles->id,
                    'uuid' => $objFiles->uuid,
                    'name' => $objFile->basename,
                    'singleSRC' => $objFiles->path,
                    'alt' => $arrMeta['title'],
                    'imageUrl' => $arrMeta['link'],
                    'caption' => $arrMeta['caption'],
                    'size' => $sb_imageSize
                );
            }
            $arrImages = array_values($arrImages);
            unset($objFiles);
            unset($multiSRC);
        }

        return $arrImages;

    }

    public static function getResizedImages()
    {
        $arrImages = static::getImages();
        $arrResizedImages = array();

        foreach ($arrImages as $key=>$arrItem)
        {
            try
            {
                $objFile = new \File($arrItem['singleSRC'], true);
            }
            catch (\Exception $e)
            {
                $objFile = new \stdClass();
                $objFile->imageSize = false;
            }

            $imgSize = $objFile->imageSize;
            $size = deserialize($arrItem['size']);

            $intMaxWidth = (TL_MODE == 'BE') ? 320 : \Config::get('maxImageWidth');

            // Adjust the image size
            if ($intMaxWidth > 0)
            {
                if ($size[0] > $intMaxWidth || (!$size[0] && !$size[1] && $imgSize[0] > $intMaxWidth))
                {
                    // See #2268 (thanks to Thyon)
                    $ratio = ($size[0] && $size[1]) ? $size[1] / $size[0] : $imgSize[1] / $imgSize[0];

                    $size[0] = $intMaxWidth;
                    $size[1] = floor($intMaxWidth * $ratio);
                }
            }

            try
            {
                $src = \Image::create($arrItem['singleSRC'], $size)->executeResize()->getResizedPath();
                $picture = \Picture::create($arrItem['singleSRC'], $size)->getTemplateData();

                if ($src !== $arrItem['singleSRC'])
                {
                    $objFile = new \File(rawurldecode($src), true);
                }
            }
            catch (\Exception $e)
            {
                \System::log('Image "' . $arrItem['singleSRC'] . '" could not be processed: ' . $e->getMessage(), __METHOD__, TL_ERROR);

                $src = '';
                $picture = array('img'=>array('src'=>'', 'srcset'=>''), 'sources'=>array());
            }

            $arrResizedImages[$key] = array
            (
                'name'      => $arrItem['name'],
                'singleSRC' => $objFile->path,
                'alt'       => $arrItem['alt'],
                'imageUrl'  => $arrItem['imageUrl'],
                'caption'   => $arrItem['caption']
            );
        }

        return $arrResizedImages;
    }

    public static function getPageImage($strType='images')
    {
        $Hook = new HookPageimage();
        return $Hook->piReplaceInsertTags('sb_'.$strType);
    }
}