<?php

namespace Webkul\WooCommerceBundle\Connector\Reader\Import;

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

$obj = new ClassDefinationForCompatibility();
$obj->objectCreate();
class FamilyVariantImportReader implements
    \ItemReaderInterface,
    \StepExecutionAwareInterface,
    \FlushableInterface
{
   

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

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

    protected $connectorService;

    protected $data = [];
    protected $startCount = 0;

    protected $page = 1;
    protected $params;

    const ACTION_GET_VARIABLE_PRODUCT = "getAllVariableProductByPage";
    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'];
    }

    protected function getFamilyVariants()
    {
        $familyVariant = [];
        $params = $this->stepExecution->getJobParameters()->all();
        $exportProfile = (isset($params['exportProfile'])) ? $params['exportProfile'] : "";
        while (empty($familyVariant)) {
            $result = $this->connectorService->requestApiAction(
                self::ACTION_GET_VARIABLE_PRODUCT,
                [],
                ["page" => $this->page, "type" => "variable", "exportProfile" => $exportProfile]
            );
            
            if (count($result) <= 1) {
                return null;
            }
            $familyVariant = $this->format($result);
            $this->page++;

            if ($familyVariant) {
                return $familyVariant;
            }
        }
    }

    public function read()
    {
        if (current($this->data) == false) {
            $familyVariants = $this->getFamilyVariants();
            if ($familyVariants) {
                $this->data = $familyVariants;
            } else {
                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(current($this->data), $e);
            }

           
            return $item;
        }
       

        return null;
    }

    public function format($results)
    {
        $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);
        }

        $familyVariant = [];
       
        foreach ($results as $result) {
            if (!empty($result['variations'])) {
                $attributes = $result['attributes'];
                $name = [];
                foreach ($attributes as $attribute) {
                    if ($attribute['variation'] == true) {
                        $code = $this->connectorService->convertToCode($attribute['name']);
                        
                        $checkAttr = $this->checkExistAttr($code);
                        if ($checkAttr) {
                            $name[] = $checkAttr;
                        }
                    }
                }
                
                $mapped = $this->connectorService->getMultiSetting('settings');
                $codes = $this->connectorService->getAttributeCodes('pim_catalog_price_collection');
                $priceAttr = [];
                
                foreach ($mapped as $map) {
                    if (in_array($map, $codes)) {
                        $priceAttr[] = $map;
                    }
                }

                if (!empty($name)) {
                    sort($name);
                    $code = "woocommerce_".implode("_", $name);
                    $label = "by ".implode(" & ", $name);
                    
                    $variantAttr = !empty($priceAttr) ? ",".implode(',', $priceAttr) : '';
                    $familyVariant[]=[
                                    'code' =>$code,
                                    'family' => "WooCommerce",
                                    'label-'.$locale => $label,
                                    'variant-axes_1' => implode(",", $name) ,
                                    'variant-attributes_1' => "sku".$variantAttr
                            ];
                }
            }
        }

        return $familyVariant;
    }

    public function checkExistAttr($key)
    {
        $codes = $this->connectorService->getAttributeCodes('pim_catalog_simpleselect');
        foreach ($codes as $code) {
            if (strtolower($key) == strtolower($code)) {
                return $code;
            }
        }

        return null;
    }

    /**
     * {@inheritdoc}
     */
    

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