<?php
/**
 * @author  Magediary
 * @package Magediary_ProductQuestion
 */

namespace Magediary\ProductQuestion\Model;

use Magediary\ProductQuestion\Api\AnswerRepositoryInterface;
use Magediary\ProductQuestion\Api\Data\AnswerInterface;
use Magediary\ProductQuestion\Api\Data\AnswerSearchResultsInterfaceFactory;
use Magediary\ProductQuestion\Api\Data\AnswerInterfaceFactory;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Exception\CouldNotDeleteException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Reflection\DataObjectProcessor;
use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface;
use Magediary\ProductQuestion\Model\ResourceModel\Answer as ResourceAnswer;
use Magediary\ProductQuestion\Model\ResourceModel\Answer\CollectionFactory as AnswerCollectionFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface;
use Magento\Framework\Api\ExtensibleDataObjectConverter;

class AnswerRepository implements AnswerRepositoryInterface
{
    /**
     * @var ResourceAnswer
     */
    protected $resource;

    /**
     * @var AnswerFactory
     */
    protected $answerFactory;

    /**
     * @var AnswerCollectionFactory
     */
    protected $answerCollectionFactory;

    /**
     * @var AnswerSearchResultsInterfaceFactory
     */
    protected $searchResultsFactory;

    /**
     * @var DataObjectHelper
     */
    protected $dataObjectHelper;

    /**
     * @var DataObjectProcessor
     */
    protected $dataObjectProcessor;

    /**
     * @var AnswerInterfaceFactory
     */
    protected $dataAnswerFactory;

    /**
     * @var JoinProcessorInterface
     */
    protected $extensionAttributesJoinProcessor;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var CollectionProcessorInterface
     */
    private $collectionProcessor;

    /**
     * @var ExtensibleDataObjectConverter
     */
    protected $extensibleDataObjectConverter;

    /**
     * @param ResourceAnswer $resource
     * @param AnswerFactory $answerFactory
     * @param AnswerInterfaceFactory $dataAnswerFactory
     * @param AnswerCollectionFactory $answerCollectionFactory
     * @param AnswerSearchResultsInterfaceFactory $searchResultsFactory
     * @param DataObjectHelper $dataObjectHelper
     * @param DataObjectProcessor $dataObjectProcessor
     * @param StoreManagerInterface $storeManager
     * @param CollectionProcessorInterface $collectionProcessor
     * @param JoinProcessorInterface $extensionAttributesJoinProcessor
     * @param ExtensibleDataObjectConverter $extensibleDataObjectConverter
     */
    public function __construct(
        ResourceAnswer $resource,
        AnswerFactory $answerFactory,
        AnswerInterfaceFactory $dataAnswerFactory,
        AnswerCollectionFactory $answerCollectionFactory,
        AnswerSearchResultsInterfaceFactory $searchResultsFactory,
        DataObjectHelper $dataObjectHelper,
        DataObjectProcessor $dataObjectProcessor,
        StoreManagerInterface $storeManager,
        CollectionProcessorInterface $collectionProcessor,
        JoinProcessorInterface $extensionAttributesJoinProcessor,
        ExtensibleDataObjectConverter $extensibleDataObjectConverter
    ) {
        $this->resource = $resource;
        $this->answerFactory = $answerFactory;
        $this->answerCollectionFactory = $answerCollectionFactory;
        $this->searchResultsFactory = $searchResultsFactory;
        $this->dataObjectHelper = $dataObjectHelper;
        $this->dataAnswerFactory = $dataAnswerFactory;
        $this->dataObjectProcessor = $dataObjectProcessor;
        $this->storeManager = $storeManager;
        $this->collectionProcessor = $collectionProcessor;
        $this->extensionAttributesJoinProcessor = $extensionAttributesJoinProcessor;
        $this->extensibleDataObjectConverter = $extensibleDataObjectConverter;
    }

    /**
     * @inheritdoc
     */
    public function save(
        AnswerInterface $answer
    ) {
        /* if (empty($answer->getStoreId())) {
            $storeId = $this->storeManager->getStore()->getId();
            $answer->setStoreId($storeId);
        } */

        $answerData = $this->extensibleDataObjectConverter->toNestedArray(
            $answer,
            [],
            AnswerInterface::class
        );

        $answerModel = $this->answerFactory->create()->setData($answerData);

        try {
            $this->resource->save($answerModel);
        } catch (\Exception $exception) {
            throw new CouldNotSaveException(__(
                'Could not save the answer: %1',
                $exception->getMessage()
            ));
        }
        return $answerModel->getDataModel();
    }

    /**
     * @inheritdoc
     */
    public function getById($answerId)
    {
        $answer = $this->answerFactory->create();
        $this->resource->load($answer, $answerId);
        if (!$answer->getId()) {
            throw new NoSuchEntityException(__('Answer with id "%1" does not exist.', $answerId));
        }
        return $answer->getDataModel();
    }

    /**
     * @inheritdoc
     */
    public function getList(
        \Magento\Framework\Api\SearchCriteriaInterface $criteria
    ) {
        $collection = $this->answerCollectionFactory->create();

        $this->extensionAttributesJoinProcessor->process(
            $collection,
            AnswerInterface::class
        );

        $this->collectionProcessor->process($criteria, $collection);

        $searchResults = $this->searchResultsFactory->create();
        $searchResults->setSearchCriteria($criteria);

        $items = [];
        foreach ($collection as $model) {
            $items[] = $model->getDataModel();
        }

        $searchResults->setItems($items);
        $searchResults->setTotalCount($collection->getSize());
        return $searchResults;
    }

    /**
     * @inheritdoc
     */
    public function delete(
        AnswerInterface $answer
    ) {
        try {
            $answerModel = $this->answerFactory->create();
            $this->resource->load($answerModel, $answer->getAnswerId());
            $this->resource->delete($answerModel);
        } catch (\Exception $exception) {
            throw new CouldNotDeleteException(__(
                'Could not delete the Answer: %1',
                $exception->getMessage()
            ));
        }
        return true;
    }

    /**
     * @inheritdoc
     */
    public function deleteById($answerId)
    {
        return $this->delete($this->getById($answerId));
    }
}
