<?php

namespace Webkul\WooCommerceBundle\Connector\Reader\Import;

use Webkul\WooCommerceBundle\Services\WooCommerceConnector;
use Webkul\WooCommerceBundle\Listener\ClassDefinationForCompatibility;

$obj = new ClassDefinationForCompatibility();
$obj->objectCreate();

class FamilyImportReader implements
    \ItemReaderInterface,
    \StepExecutionAwareInterface,
    \FlushableInterface
{
   

    /** @var StepExecution */
    protected $stepExecution;

    /** @var \ArrayConverterInterface */
    protected $converter;

    protected $connectorService;

    protected $data;

    const ACTION_GET_ATTRIBUTE = "getAllOption";
    const AKENEO_ATTRIBUTE_ENTITY_NAME = 'attribute';
    /**
     * @param \ArrayConverterInterface $converter
     */
    public function __construct(\ArrayConverterInterface $converter, WooCommerceConnector $connectorService)
    {
        $this->converter = $converter;
        $this->connectorService = $connectorService;
    }

    public function read()
    {
        
        $params = $this->stepExecution->getJobParameters()->all();
        
        if (null === $this->data) {
            $scope = $params['filters']['structure']['scope'];
            $locale = $params['filters']['structure']['locale'];
            if (is_array($locale)) {
                $locale = reset($locale);
            }
            $exportProfile = (isset($params['exportProfile'])) ? $params['exportProfile'] : "";
            // $attrMappings = $this->connectorService->getMappingByEntity(self::AKENEO_ATTRIBUTE_ENTITY_NAME) ?? '';
            $attrMappings = $this->connectorService->getMappingByEntityForFamily(self::AKENEO_ATTRIBUTE_ENTITY_NAME, $exportProfile) ?? '';
            
            $mapped = $this->connectorService->getOtherMappings();
            $defaultImages = isset($mapped['images']) ? reset($mapped['images']) : '';
           
            $attributes = [];

            foreach($attrMappings as $attr) {
                $code = $attr->getCode();
                $isAttributeExist = $this->connectorService->getAttributeByCode($code);
                if($isAttributeExist) {
                    $attributes[] = $code;
                }
            }
            
            $image = $this->connectorService->getMultiSetting('other_mappings');
            $maxImage = isset($image['maximage']) ? $image['maximage'] : 0;
            
            for ($i = $maxImage ;$i>0 ; $i--) {   
                $code = "image".$i;
                $isImageAttributeExist = $this->connectorService->getAttributeByCode($code);
                if($isImageAttributeExist){
                    $attributes[] = $code;
                }
            }
            
            $mapped = $this->connectorService->getMultiSetting('settings');
            
            foreach ($mapped as $map) {
                $attributes[] = $map;
            }
            $otherMapping = $this->connectorService->getOtherMappings();   
            if (!empty($otherMapping['images'])) {
                foreach($otherMapping['images'] as $value) {
                    $attributes[] = $value;
                }
            }
            if (!empty($otherMapping['custom_fields'])) {
                foreach($otherMapping['custom_fields'] as $value) {
                    $attributes[] = $value;
                }
            }
            $attributes = $this->filterAttribute(array_unique(array_filter($attributes)));
            $family = [];
            $family[] = [
                            'code' => 'WooCommerce',
                            'label-'.$locale => 'WooCommerce',
                            'attributes' => implode(',', array_filter($attributes)), 
                            'attribute_as_image' => $defaultImages,
                            'attribute_as_label' => 'sku',
                            'requirements-'.$scope => 'sku' 
                        ]; 

            $this->data = $family;
        }
        
        if ($data = current($this->data)) {

            $item = [];
            
            foreach ($data as $attributeName => $attributeValue) {
                $item[$attributeName] = (string) $attributeValue;  
            }
        
            next($this->data);

            if (null !== $this->stepExecution) {
                $this->stepExecution->incrementSummaryInfo('item_position');
            }
            
            try {
                $item = $this->converter->convert($item);
                
            } catch (\DataArrayConversionException $e) {
                $this->skipItemFromConversionException($this->data->current(), $e);
            }

            return $item;
        }

        return null;

    }

    /**
     * {@inheritdoc}
     */
    
    public function filterAttribute($attribute) 
    {
        $attributes = [];
        foreach($attribute as $code) {
            $attr = $this->connectorService->getAttributeCode($code);
            if($attr)
                $attributes[] = $attr;
        }

        return $attributes;
    }
    public function flush()
    {
        $this->xml = null;
    }

    /**
     * {@inheritdoc}
     */
    public function setStepExecution(\StepExecution $stepExecution)
    {
        $this->stepExecution = $stepExecution;
        $this->connectorService->setStepExecution($stepExecution);
    }

    /**
     * @param array                        $item
     * @param \DataArrayConversionException $exception
     *
     * @throws \InvalidItemException
     * @throws \InvalidItemFromViolationsException
     */
    protected function skipItemFromConversionException(array $item, \DataArrayConversionException $exception)
    {
        if (null !== $this->stepExecution) {
            $this->stepExecution->incrementSummaryInfo('skip');
        }

        if (null !== $exception->getViolations()) {
            throw new \InvalidItemFromViolationsException(
                $exception->getViolations(),
                new \FileInvalidItem($item, $this->stepExecution->getSummaryInfo('item_position')),
                [],
                0,
                $exception
            );
        }

        $invalidItem = new \FileInvalidItem(
            $item,
            $this->stepExecution->getSummaryInfo('item_position')
        );

        throw new \InvalidItemException($exception->getMessage(), $invalidItem, [], 0, $exception);
    }
}
