<?php

namespace Webkul\WooCommerceBundle\Connector\Reader\Import;

use Webkul\WooCommerceBundle\Services\WooCommerceConnector;
use Symfony\Component\HttpFoundation\Response;
use Webkul\WooCommerceBundle\Listener\ClassDefinationForCompatibility;

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

class AttributeOptionImportReader implements
    \ItemReaderInterface,
    \StepExecutionAwareInterface,
    \InitializableInterface
{
   

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

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

    protected $connectorService;

    protected $data = [];

    protected $page;

    protected $items;

    protected $scope;

    protected $locale;

    protected $mappings;

    protected $params;

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

    public function initialize()
    {
        $this->items = [];
        $this->params = $this->stepExecution->getJobParameters()->all();
        $this->scope = $this->params['filters']['structure']['scope'];
        $this->locale = is_array($this->params['filters']['structure']['locale']) ? reset($this->params['filters']['structure']['locale']) : $this->params['filters']['structure']['locale'];
        $this->mappings = $this->connectorService->getMappingByEntity(self::AKENEO_ATTRIBUTE_ENTITY_NAME) ?? [];
    }

    public function getAttributeOption($mapping)
    {
        $this->page = 1;
        $attributeOptions = [];
        $exportProfile = (isset($this->params['exportProfile'])) ? $this->params['exportProfile'] : "";
        while (!empty($mapping)) {
            $result = $this->connectorService->requestApiAction(
                    self::ACTION_GET_ATTRIBUTE,
                    [],
                    ["attribute"=>$mapping->getExternalId(),"page"=>$this->page, "exportProfile" => $exportProfile]
                );

            $this->page++;
            
            if(isset($result["code"]) && $result["code"] != Response::HTTP_OK  ){

                break;
            }
            if (count($result) > 1) {

                $selectedAttrCodes = $this->connectorService->getSelectAttributeCodes();
                $multiSelectedAttrCodes = $this->connectorService->getMultiSelectAttributeCodes();
                //dump($selectedAttrCodes,$selectedAttrCodes); die;
               // dump($selectedAttrCodes);
                if ((in_array($mapping->getCode(), $selectedAttrCodes)) ||
                        (in_array($mapping->getCode(), $multiSelectedAttrCodes))) {
                    $attributeOption = $this->format($result, $mapping->getCode());
                }
                    
                if (!empty($attributeOption)) {
                    foreach ($attributeOption as $option) {
                        $attributeOptions[] = $option;
                    }
                }
            } else {
                break;
            }
        }

        return $attributeOptions;
    }

    public function getDataFromMapping()
    {
        while ($mapping = current($this->mappings)) {
            $data = $this->getAttributeOption($mapping);
            next($this->mappings);
            if (!empty($data)) {
                return $data;
            }
        } 
    
        return [];
    }
    public function read()
    {
        if(current($this->data) === false) {
            $this->data = $this->getDataFromMapping();
            if(empty($this->data)) {
                return null;
            }
        }
        
        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, $parentCode)
    {
        $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);
        }
        $attributeOption = [];
        if ($results['code'] == '200') {
            unset($results['code']);

            foreach ($results as $result) {
                $code = $this->connectorService->convertToCode($result['slug']);
                
                if (strlen($code) > 80) {
                    dump($result['slug']);
                    $this->stepExecution->addWarning('Attribute Option Code is too large.', [], new \DataInvalidItem([]));
                    continue;
                }
                $attributeOption[] = [
                                'code' => $code,
                                'label-'.$locale => $result['name'],
                                'attribute' => $parentCode,
                                'sort_order' => 1
                            ];
            }
            
            return $attributeOption;
        }

        return null;
    }

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

    /**
     * {@inheritdoc}
     */
    public function setStepExecution(\StepExecution $stepExecution)
    {
        $this->stepExecution = $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);
    }
}
