<?php

namespace Webkul\WooCommerceBundle\Connector\Reader\Import;

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

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

class AttributeImportReader implements
    \ItemReaderInterface,
    \StepExecutionAwareInterface,
    \FlushableInterface
{
    use DataMappingTrait;

    

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

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

    protected $connectorService;

    protected $data;

    const ACTION_GET_ATTRIBUTE = "getAttributes";
    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()
    {
        
       // return null;
        if (null === $this->data) {
            $params = $this->stepExecution->getJobParameters()->all();
            $exportProfile = (isset($params['exportProfile'])) ? $params['exportProfile'] : "";
            $result = $this->connectorService->requestApiAction(
                self::ACTION_GET_ATTRIBUTE,
                [],
                ["exportProfile"=> $exportProfile]
            );
            
           
            $attribute = $this->format($result,$exportProfile); 
            
            $this->data = $attribute;
            //dump($this->data); die;
        }
        
        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 format($results,$exportProfile)
    {
        
        $params = $this->stepExecution->getJobParameters()->all();
        $localeCodes = $params['filters']['structure']['locales'];
        $currency = $params['filters']['structure']['currency'];
        $scope = $params['filters']['structure']['scope'];
        $locale = $params['filters']['structure']['locale'];
        
        if (is_array($locale)) {
            $locale = reset($locale);
           
        }
        
        if ($results['code'] == '200') {
            
            unset($results['code']);
            $attribute = [];
            foreach ($results as $result) {
                $code = str_replace('pa_', '', $result['slug']);
                $code = $this->connectorService->convertToCode($code);
                
                $type = $result['type'];
                
                $mapping = $this->connectorService->getMappingByCode($code, self::AKENEO_ATTRIBUTE_ENTITY_NAME,$exportProfile) ?? '';
                
                $isAttributeExist = $this->connectorService->getAttributeByCode($code);
                
                $this->connectorService->addOrUpdateMapping($mapping, $code, 'attribute', $result['id'],$exportProfile,$relatedId = null, $jobInstanceId = null);
                
                if ($isAttributeExist) {
                    
                    if (strlen($code) > 80) {
                        $this->stepExecution->addWarning('Attribute Option Code is too large.', [], new \DataInvalidItem([]));
                        continue;
                    }
                    
                    $localizable = $isAttributeExist->isLocalizable() ? 1 : 0 ;
                    $scopable = $isAttributeExist->isScopable() ? 1 : 0;
                    $unique = $isAttributeExist->isUnique() ? 1 : 0;
                    $usageinGridFilter = $isAttributeExist->isUseableAsGridFilter() ? 1 : 0;
                    $group = $isAttributeExist->getGroup() ? $isAttributeExist->getGroup()->getCode() : 'other';
                   
                    if ($type == "select" || $type == "text") {
                        
                        $attribute[] = [
                                        'code' => $isAttributeExist->getCode(),
                                        'type' => $isAttributeExist->getAttributeType(),
                                        'group' => $group,
                                        'unique' => $unique,
                                        'useable_as_grid_filter' => $usageinGridFilter,
                                        'sort_order' => $isAttributeExist->getSortOrder(),
                                        'localizable' => $localizable,
                                        'scopable' => $scopable,
                                        "label-".$locale => $result['name']
                                    ];
                                                   
                    } else {
                        $this->stepExecution->addWarning('Attribute is not a valid Type.', [], new \DataInvalidItem([]));
                        continue;
                    } 

                } else {
                   
                    if (strlen($code) > 80) {
                        $this->stepExecution->addWarning('Attribute Option Code is too large.', [], new \DataInvalidItem([]));
                        continue;
                    }
                    
                    if ($type == "select") {
                        $attribute[] = [
                                        'code' => $code,
                                        'type' => 'pim_catalog_simpleselect',
                                        'group' => 'other',
                                        'unique' => 0,
                                        'useable_as_grid_filter' => 0,
                                        'sort_order' => 0,
                                        'localizable' => 0,
                                        'scopable' => 0,
                                        "label-".$locale => $result['name']
                                    ];
                    } elseif ($type == "text") {
                        $attribute[] = [    
                                        'code' => $code,
                                        'type' => 'pim_catalog_text',
                                        'group' => 'other',
                                        'unique' => 0,
                                        'useable_as_grid_filter' => 0,
                                        'sort_order' => 0,
                                        'localizable' => 0,
                                        'scopable' => 0,
                                        "label-".$locale => $result['name']
                                    ];
                    }
                }
            }
          
            return $attribute;
        }

        return null;
    }

    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);
    }
}
