<?php

namespace Webkul\Magento2Bundle\Connector\Reader;

use Doctrine\Common\Persistence\ObjectRepository;
use Webkul\Magento2Bundle\Services\Magento2Connector;
use Webkul\Magento2Bundle\EventListener\AkeneoVersionsCompatibility;

$classLoad = new AkeneoVersionsCompatibility();
$classLoad->checkVersionAndCreateClassAliases();

/**
 * attribute reader, basic
 */
class AttributeReader extends \AbstractReader implements
    \ItemReaderInterface,
    \InitializableInterface,
    \StepExecutionAwareInterface
{
    /** @var ObjectRepository */
    protected $repository;

    /**
     * @param ObjectRepository $repository
     */
    public function __construct(ObjectRepository $repository, Magento2Connector $connectorService)
    {
        $this->repository = $repository;
        $this->connectorService = $connectorService;
    }

    /**
     * {@inheritdoc}
     */
    protected function getResults()
    {
        $mappings = $this->connectorService->getOtherMappings();
        
        if (isset($mappings['configurable_product_status'])) {
            unset($mappings['configurable_product_status']);
        }
        
        $jobSelectedAttributes = [];
        if (isset($this->stepExecution->getJobParameters()->get('filters')['attributeExport'])) {
            $jobSelectedAttributes = $this->stepExecution->getJobParameters()->get('filters')['attributeExport'];
        }

        $selectedAttrs = $jobSelectedAttributes;
        $selectedAttrs = $mappings ['custom_fields'];
        
        $selectedAttrs = array_diff($selectedAttrs, $this->reservedAttributes);
        
        $attributes = $this->findAttributesByCodes($selectedAttrs);

        return new \ArrayIterator($attributes);
    }

    protected function findAttributesByCodes($codes)
    {
        return $this->repository->createQueryBuilder('a')
                ->andWhere('a.code in (:codes)')
                ->setParameter('codes', $codes)
                ->getQuery()->getResult();
    }


    protected $reservedAttributes = [
        'status',
        'visibility',
        'quantity_and_stock_status',
        'gift_message_available',
        'tax_class_id'
    ];
}
