<?php

use KupShop\CommentsBundle\Comment;
use KupShop\CommentsBundle\Util\CommentList;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

function smarty_function_insert_comments($params, &$smarty)
{
    if (empty($params['id'])) {
        throw new InvalidArgumentException('Missing required argument \'id\'');
    }

    $default = [
        'type' => Comment::TYPE_PRODUCT,
        'template' => 'comments/comments.tpl',
    ];

    $params = array_merge($default, $params);

    $totalCount = 0;

    /** @var CommentList $commentList */
    $commentList = ServiceContainer::getService(CommentList::class);

    $pager = $commentList->createPager($params['page'] ?? 1);

    $commentList->andSpec($pager->getSpec());
    $comments = $commentList->getComments((int) $params['id'], $params['type'], $params['id_language'] ?? null, $totalCount);

    $pager->setTotal($totalCount);

    $data = [
        'config' => [
            'objectId' => $params['id'],
            'type' => $params['type'],
        ],
        'pager' => $pager,
        'comments' => $comments,
        'totalCount' => $totalCount,
    ];

    if ($params['assign'] ?? null) {
        $smarty->assign($params['assign'], $data);
    } else {
        $_smarty_tpl_vars = $smarty->tpl_vars;
        echo $smarty->_subTemplateRender($params['template'], $smarty->cache_id, $smarty->compile_id, 0, null, ['data' => $data], 0, false);
        $smarty->tpl_vars = $_smarty_tpl_vars;
    }
}
