<?php
/**
 * @author Aitoc Team
 * @copyright Copyright (c) 2020 Aitoc (https://www.aitoc.com)
 * @package Aitoc_PreOrders
 */

/**
 * Copyright © 2018 Aitoc. All rights reserved.
 * Developed by Alex Yakimovich
 */

namespace Aitoc\PreOrders\Model;

use Aitoc\PreOrders\Api\ProductAttributesRepositoryInterface;
use Aitoc\PreOrders\Api\Data\ProductAttributesInterface;
use Aitoc\PreOrders\Model\ResourceModel\ProductAttributes as ProductAttributesResource;
use Aitoc\PreOrders\Model\ResourceModel\ProductAttributes\CollectionFactory
    as ProductAttributesCollectionFactory;
use Magento\Framework\Exception\CouldNotDeleteException;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Api\SearchCriteriaInterface;
use Aitoc\PreOrders\Api\Data\ProductAttributesSearchResultsInterfaceFactory;
use Aitoc\PreOrders\Api\Data\ProductAttributesSearchResultsInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Exception\InputException;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 * @SuppressWarnings(PHPMD.LongVariable)
 */
class ProductAttributesRepository implements ProductAttributesRepositoryInterface
{
    /**
     * @var ProductAttributesResource
     */
    private $productAttributesResource;

    /**
     * @var ProductAttributesFactory
     */
    private $productAttributesFactory;

    /**
     * @var ProductAttributesCollectionFactory
     */
    private $productAttributesCollectionFactory;

    /**
     * @var ProductAttributesSearchResultsInterfaceFactory
     */
    private $productAttributesSearchResultsFactory;

    /**
     * @var SearchCriteriaBuilder
     */
    private $searchCriteriaBuilder;

    /**
     * @var RepositoryResolver
     */
    private $repositoryResolver;

    /**
     * @var array
     */
    private $settings = [];

    /**
     * @param ProductAttributesResource $productAttributesResource
     * @param ProductAttributesFactory $productAttributesFactory
     * @param ProductAttributesCollectionFactory $productAttributesCollectionFactory
     * @param ProductAttributesSearchResultsInterfaceFactory $productAttributesSearchResultsFactory
     * @param SearchCriteriaBuilder $searchCriteriaBuilder
     */
    public function __construct(
        ProductAttributesResource $productAttributesResource,
        ProductAttributesFactory $productAttributesFactory,
        ProductAttributesCollectionFactory $productAttributesCollectionFactory,
        ProductAttributesSearchResultsInterfaceFactory $productAttributesSearchResultsFactory,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        RepositoryResolver $repositoryResolver
    ) {
        $this->productAttributesResource = $productAttributesResource;
        $this->productAttributesFactory = $productAttributesFactory;
        $this->productAttributesCollectionFactory = $productAttributesCollectionFactory;
        $this->productAttributesSearchResultsFactory = $productAttributesSearchResultsFactory;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->repositoryResolver = $repositoryResolver;
    }

    /**
     * Save entity.
     *
     * @param ProductAttributesInterface $settings
     * @return ProductAttributesInterface
     * @throws CouldNotSaveException
     * @throws NoSuchEntityException
     */
    public function save(ProductAttributesInterface $settings)
    {
        if ($settings->getEntityId()) {
            /** @var ProductAttributes $settings */
            $settings = $this->get($settings->getEntityId())->addData($settings->getData());
        }

        try {
            $this->productAttributesResource->save($settings);
            if ($settings->getEntityId()) {
                unset($this->settings[$settings->getEntityId()]);
            }
        } catch (\Exception $e) {
            throw new CouldNotSaveException(__('Unable to save settings %1', $settings->getEntityId()));
        }
        return $settings;
    }

    /**
     * @param int $attributeCode
     * @param int $storeId
     * @return ProductAttributesInterface|mixed
     * @throws NoSuchEntityException
     */
    public function get($entityId)
    {
        if (!isset($this->settings[$entityId])) {
            $settings = $this->productAttributesFactory->create();
            $this->productAttributesResource->load($settings, $entityId);
            if (!$settings->getEntityId()) {
                throw new NoSuchEntityException(__('Settings with specified ID "%1" not found.', $entityId));
            }
            $this->settings[$entityId] = $settings;
        }
        return $this->settings[$entityId];
    }

    /**
     * Retrieve entity by product id and store id.
     *
     * @param $productId
     * @param $attributeCode
     * @param int $storeId
     * @return ProductAttributesInterface|mixed
     */
    public function getByProductId($productId, $attributeCode, $storeId = 0)
    {
        $searchCriteria = $this->searchCriteriaBuilder
            ->addFilter(ProductAttributesInterface::PRODUCT_ID, $productId)
            ->addFilter(ProductAttributesInterface::ATTRIBUTE_CODE, $attributeCode)
            ->addFilter(ProductAttributesInterface::STORE_ID, $storeId)
            ->create();
        $items = $this->getList($searchCriteria)->getItems();
        if (count($items)) {
            $model = reset($items);
        }
        return  isset($model) ? $model : false;
    }

    /**
     * Load settings collection by given search criteria
     *
     * @param SearchCriteriaInterface $criteria
     * @return ProductAttributesSearchResultsInterface|mixed
     * @throws InputException
     */
    public function getList(SearchCriteriaInterface $criteria)
    {
        $collection = $this->productAttributesCollectionFactory->create();
        return $this->repositoryResolver->getList($criteria, $collection, $this->productAttributesSearchResultsFactory);
    }

    /**
     * @param ProductAttributesInterface $model
     * @return bool
     * @throws CouldNotDeleteException
     */
    public function delete(ProductAttributesInterface $model)
    {
        try {
            $this->productAttributesResource->delete($model);
        } catch (\Exception $e) {
            throw new CouldNotDeleteException(__($e->getMessage()));
        }
        return true;
    }
}
