<?php

namespace Autogedal\Extend\Model\Answer;

use Magediary\ProductQuestion\Model\ResourceModel\Answer\Collection;
use Magediary\ProductQuestion\Model\ResourceModel\Answer\CollectionFactory;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Ui\DataProvider\AbstractDataProvider;
use Magento\Framework\UrlInterface;
use Magediary\ProductQuestion\Api\QuestionRepositoryInterface;

class DataProvider extends \Magediary\ProductQuestion\Model\Answer\DataProvider
{
    /**
     * @var Collection
     */
    protected $collection;

    /**
     * @var DataPersistorInterface
     */
    protected $dataPersistor;

    /**
     * @var array
     */
    protected $loadedData;
    protected $urlBuilder;
    protected $questionRepository;

    public function __construct(
        $name,
        $primaryFieldName,
        $requestFieldName,
        CollectionFactory $collectionFactory,
        DataPersistorInterface $dataPersistor,
        UrlInterface $urlBuilder,
        QuestionRepositoryInterface $questionRepository,
        array $meta = [],
        array $data = []
    ) {
        $this->urlBuilder = $urlBuilder;
        $this->collection = $collectionFactory->create();
        $this->dataPersistor = $dataPersistor;
         $this->questionRepository = $questionRepository;
        parent::__construct(
            $name,
            $primaryFieldName,
            $requestFieldName,
            $collectionFactory,
            $dataPersistor,
            $meta,
            $data
        );
    }

    /**
     * Get data
     *
     * @return array
     */
    public function getData()
    {
        if (isset($this->loadedData)) {
            return $this->loadedData;
        }
        $items = $this->collection->getItems();
        foreach ($items as $model) {
            $data = $model->getData();
            $questionId = $model->getQuestionId();
            if ($questionId && $model->getId()) {
                $url = $this->urlBuilder->getUrl(
                    'magediary_productquestion/question/edit',
                    ['question_id' => $questionId]
                );
                $question = $this->questionRepository->getById($questionId);
                $data['question_url'] = '<a href="' . $url . '" target="_blank" rel="noopener">'.$question->getDetail().'</a>';
            }

            $this->loadedData[$model->getId()] = $data;

        }
        $data = $this->dataPersistor->get('magediary_question_answer');

        if (!empty($data)) {
            $model = $this->collection->getNewEmptyItem();
            $model->setData($data);
            $this->loadedData[$model->getId()] = $model->getData();
            $this->dataPersistor->clear('magediary_question_answer');
        }

        return $this->loadedData;
    }
}
