<?php

/**
 * Smarty plugin.
 */

use KupShop\ContentBundle\Entity\Wrapper\PhotoWrapper;
use KupShop\ContentBundle\Util\ImageLocator;
use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\KupShopBundle\Util\System\UrlFinder;
use Symfony\Component\ErrorHandler\Exception\SilencedErrorContext;

/**
 * Smarty {url} plugin.
 *
 * Type:     function<br>
 * Name:     get_photo<br>
 * Purpose:  return array describing image
 *
 * @param array                    $params parameters
 * @param Smarty_Internal_Template $smarty template object
 *
 * @return string
 */
function smarty_function_get_photo($params, &$smarty)
{
    $photo = null;
    $type = 'product';
    $id = null;
    $photoId = null;
    $size = null;
    $assign = null;
    $lang = null;
    $absolute = null;
    $time = null;
    $version = 'desktop';

    extract($params);

    // validate version (desktop, tablet, mobile)
    if (!in_array($version, ['desktop', Photos::PHOTO_VERSION_MOBILE, Photos::PHOTO_VERSION_TABLET])) {
        throw new InvalidArgumentException('Invalid version of image!');
    }

    if ($version === 'desktop') {
        $version = Photos::PHOTO_VERSION_DESKTOP;
    }

    static $imageLocator = null;
    if (!$imageLocator) {
        $imageLocator = ServiceContainer::getService(ImageLocator::class);
    }

    // HACK: Dočasná zpetná kompatibilita kvůli přejmenování 'image' parametru na 'size'
    if (is_null($size) && !is_null($params['image'])) {
        $size = $params['image'];
    }

    $smartyReturn = function ($ret) use (&$smarty, $assign, $absolute, $params) {
        static $urlFinder = null;

        if (!$urlFinder) {
            $urlFinder = ServiceContainer::getService(UrlFinder::class);
        }

        if ($params['gifs'] ?? false) {
            if (!$absolute) {
                $ret = $urlFinder->shopUrl($ret);
            } else {
                $ret = $urlFinder->shopUrlAbsolute($ret);
            }
        } else {
            if (!$absolute) {
                $ret = $urlFinder->staticUrl($ret);
            } else {
                $ret = $urlFinder->staticUrlAbsolute($ret);
            }
        }

        if (!empty($assign)) {
            $smarty->assign($assign, $ret);
        } else {
            return $ret;
        }

        return null;
    };

    // HACK: Dočasně podporujeme v 'id' parametru pole, stejně jako v 'photo' parametru
    if (is_array($id) && is_null($photo)) {
        $photo = $id;
    }

    if (is_array($photo)) {
        if (empty($photo)) {
            $id = 0;
        } elseif (isset($photo['type']) && $photo['type'] == $imageLocator->getTypeName($size)) {
            return $smartyReturn($photo['src']);
        } else {
            if (!array_key_exists('date_update', $photo)) {
                $sentry = getRaven();
                $sentry->captureMessage(
                    "get_photo: chybí parametr 'date_update' v poli s obrázkem"
                );
                user_error("get_photo: chybí parametr 'date_update' v poli s obrázkem");
            }

            $id = $photo['id'];
            $time = $photo['date_update'];
            $photo = null;
        }
    } elseif ($photo instanceof PhotoWrapper) {
        $photo = $photo->getObject();
        $id = $photo->getId();
        $time = $photo->getDate()->getTimestamp();
        $photo = null;
    } elseif ($photo instanceof \KupShop\ContentBundle\Entity\Image) {
        $id = $photo->getId();
        $time = $photo->getDateUpdated()->getTimestamp();
        $photo = null;
    } else {
        $id = (int) $id;
    }

    if (!$photo) {
        if (is_null($id) || is_null($size)) {
            $sentry = getRaven();
            $sentry->captureMessage(
                "get_photo: pokud chybi parametr 'photo', musi byt aspon parametr 'id' (id obrázku) a 'size' (velikost obrázku)"
            );

            user_error("get_photo: pokud chybi parametr 'photo', musi byt aspon parametr 'id' (id obrázku) a 'size' (velikost obrázku)");

            return null;
        }

        $settings = $imageLocator->getTypeConfig($size);
        if (empty($lang)) {
            $cfg = \KupShop\KupShopBundle\Config::get();
            if (!empty($settings['lang']) || ($id == 0 && !empty($cfg['Photo']['placeholder']['lang']))) {
                $lang = Contexts::get(LanguageContext::class)->getActiveId();
            }
        }

        $imagePath = $imageLocator->getPath($id, $size, 'jpg', $lang, $version);
        $ret = $imagePath;

        // Add cache busting timestamp
        if (!$time && isLocalDevelopment()) {
            $logger = ServiceContainer::getService('logger');
            $logger->error('get_photo bez data poslední změny '.$size, array_merge(['id' => $id], ['exception' => new SilencedErrorContext(1, '', 0, debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 5), 1)]));
        }

        $imageVersion = Settings::getDefault()->image_version ?? 1;

        $ret = "{$ret}?{$time}_{$imageVersion}";

        return $smartyReturn($ret);
    }

    if (!$type) {
        $sentry = getRaven();
        $sentry->captureMessage("get_photo: missing parameter 'type'");

        user_error("get_photo: missing parameter 'type'");

        return;
    }

    if (!$id) {
        $sentry = getRaven();
        $sentry->captureMessage("get_photo: missing parameter 'id'");

        user_error("get_photo: missing parameter 'id'");

        return;
    }

    $ret = null;

    switch ($type) {
        case 'section':
            if (!$size) {
                $size = 6;
            }
            $ret = getImage($id, $photo, '../section/', $size);
            break;

        case 'producer':
            if (!$size) {
                $size = 7;
            }
            $ret = getImage($id, $photo, '../producer/', $size);
            break;

        case 'payment':
            if (!$size) {
                $size = 8;
            }
            $ret = getImage($id, $photo, '../payment/', $size);
            break;

        case 'delivery':
            if (!$size) {
                $size = 9;
            }
            $ret = getImage($id, $photo, '../delivery/', $size);
            break;

        case 'article':
            if (!$size) {
                $size = 1;
            }
            if (empty($photoId) || ($ret = getImage($photoId, null, null, $size)) === false) {
                $ret = leadImage($id, $size, 'ARTICLE');
            }
            break;

        case 'product':
            if (!$size) {
                $size = 1;
            }
            if (empty($photoId) || ($ret = getImage($photoId, null, null, $size)) === false) {
                $ret = leadImage($id, $size);
            }
            break;

        default:
            echo "Non-existing photo type: {$type}";

            return;
    }

    return $smartyReturn($ret);
}
