<?php

namespace Autogedal\Extend\Block\Answer;
use Magediary\ProductQuestion\Model\Answer;

class ListView extends \Magediary\ProductQuestion\Block\Answer\ListView
{
    /**
     * Get collection of answer
     *
     * @param int $questionId
     * @return mixed
     */
    public function getAnswersCollection()
    {
        if (null === $this->_answersCollection) {
            $this->_answersCollection = $this->_answersColFactory->create()
                ->addStatusFilter(
                    Answer::STATUS_APPROVED
                )->addQuestionFilter(
                    $this->getQuestionId()
                )->setDateOrder();
            $this->_answersCollection->getSelect()->order([
                new \Zend_Db_Expr('CASE WHEN type = 3 THEN 0 ELSE 1 END ASC'),
                new \Zend_Db_Expr('created_at DESC')
            ]);
        }

        return $this->_answersCollection;
    }
    
    public function setupPager()
    {
        $collection = $this->getAnswersCollection();
        $pager = $this->getChildBlock('pager');

        if ($pager && $collection) {
            $pager->setCollection($collection);
            $pager->setAvailableLimit([10 => 10]);
                    $pager->setPageVarName('a' . $this->getQuestionId());

            $pager->setShowPerPage(false);
            $pager->setShowAmounts(false);
        }

        return $this;
    }

    /**
     * Get question id by get parameter
     *
     * @return int|null
     */
    public function getQuestionId()
    {
       return $this->getData('question_id') ?? $this->getRequest()->getParam('question_id');
    }

    /**
     * Get product id
     *
     * @return int
     */
    public function getProductId()
    {
        return $this->getData('product_id') ?? $this->getRequest()->getParam('product_id');
    }

    protected function _prepareLayout()
    {
        return $this;
    }
}
