<?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 CategoryImportReader implements \ItemReaderInterface, \StepExecutionAwareInterface, \InitializableInterface
{
    const ACTION_GET_CATEGORIES = 'getCategories';

    const AKENEO_CATEGORY_ENTITY_NAME = 'category';

    const PER_PAGE = 100;

    const DEFAULT_ORDER_BY = 'term_group';

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

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

    /** @var WooCommerceConnector */
    protected $connectorService;

    protected $page;

    protected $itemIterator;

    protected $items;

    protected $scope;

    protected $locale;

    protected $defaultParent;

    protected $childrenCategories;

    protected $params;

    /**
     * @param ArrayConverterInterface $converter
     *
     * @param WooCommerceConnector $connectorService
     */
    public function __construct(\ArrayConverterInterface $converter, WooCommerceConnector $connectorService)
    {
        $this->converter = $converter;
        $this->connectorService = $connectorService;
    }

    public function initialize()
    {
        $this->items = [];
        $this->page = 1;
        $this->params = $this->stepExecution->getJobParameters()->all();
        $this->scope = $this->params['filters']['structure']['scope'];
        $this->defaultParent = $this->connectorService->getParentCategory($this->scope);
        $this->locale = is_array($this->params['filters']['structure']['locale']) ? reset($this->params['filters']['structure']['locale']) : $this->params['filters']['structure']['locale'];
    }

    public function read()
    {
        if (null === $this->itemIterator) {
            $this->items = $this->getCategoriesByPage($this->page);
            $this->itemIterator = new \ArrayIterator([]);
            if (!empty($this->items)) {
                $this->itemIterator = new \ArrayIterator($this->items);
            }
        }

        $item = $this->itemIterator->current();
        if ($item !== null) {
            $this->stepExecution->incrementSummaryInfo('read');
            $this->itemIterator->next();
        } else {
            $this->page++;
            $this->items = $this->getCategoriesByPage($this->page);
            if (!empty($this->items)) {
                $this->itemIterator = new \ArrayIterator($this->items);
            }
            $item = $this->itemIterator->current();
            if ($item !== null) {
                $this->stepExecution->incrementSummaryInfo('read');
                $this->itemIterator->next();
            }
        }

        if (null === $item && $this->childrenCategories) {
            $childrenCategories = $this->childrenCategories;
            $this->childrenCategories = null;
            $items = $this->format($childrenCategories);
            if (!empty($this->items)) {
                $this->itemIterator = new \ArrayIterator($this->items);
            }
            $item = $this->itemIterator->current();
            if ($item !== null) {
                $this->stepExecution->incrementSummaryInfo('read');
                $this->itemIterator->next();
            }
        }
        return $item;
    }


    public function getCategoriesByPage($currentPage)
    {
        $items = [];
        $exportProfile = (isset($this->params['exportProfile'])) ? $this->params['exportProfile'] : "";
        $response = $this->connectorService->requestApiAction(
            self::ACTION_GET_CATEGORIES,
            [],
            ["page"=>$currentPage, "per_page" => self::PER_PAGE, "orderby"=>self::DEFAULT_ORDER_BY, "exportProfile"=> $exportProfile]
        );

        if (Response::HTTP_OK == $response['code'] && !empty($response[0])) {
            $items = $this->format($response);
        }

        return $items;
    }
 
    /**
     * {@inheritdoc}
     */
    public function format($results)
    {
        $categories = [];
        $exportProfile = (isset($this->params['exportProfile'])) ? $this->params['exportProfile'] : "";
        foreach ($results as $key => $result) {
            if ('code' === $key) {
                continue;
            }
            $code = $this->connectorService->convertToCode($result['slug']);
            // $isCategoryExist = $this->connectorService->getCategoryCode($code);
            if (strlen($code) > 80) {
                $this->stepExecution->addWarning('Category Option Code is too large.', [], new \DataInvalidItem([]));
                continue;
            }

            if ($result['parent'] > 0) {
                $parentMapping = $this->connectorService->getMappingByExternalId($result['parent'], self::AKENEO_CATEGORY_ENTITY_NAME,$exportProfile);
                $parent = $parentMapping ? $parentMapping->getCode() : '';
                if (!$parentMapping) {
                    $this->childrenCategories[] =  $result;
                    continue;
                }
            } else {
                $parent = $this->defaultParent;
            }

            $categories []  = [
                "code" => $code,
                "parent" => $parent,
                "labels" => [
                    $this->locale => $result['name']
                ]
            ];

            $mapping = $this->connectorService->getMappingByCode($code, self::AKENEO_CATEGORY_ENTITY_NAME, $exportProfile) ?? '';
            
            $this->connectorService->addOrUpdateMapping($mapping, $code, 'category', $result['id'], $exportProfile, $parent);
        }
        return $categories;
    }

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