<?php

namespace Webkul\WooCommerceBundle\Connector\Reader;

use Doctrine\Common\Collections\ArrayCollection;
use Webkul\WooCommerceBundle\Listener\ClassDefinationForCompatibility;

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

class CategoryReader extends \BaseReader
{
    /**
     * @param \CategoryRepositoryInterface $repository
     */
    public function __construct(\CategoryRepositoryInterface $repository, \ChannelRepository $channelRepo)
    {
        $this->repository = $repository;
        $this->channelRepo = $channelRepo;
    }

    /**
     * {@inheritdoc}
     */
    protected function getResults()
    {
        $filters = $this->stepExecution->getJobParameters()->get('filters');
        $channelCode = !empty($filters['structure']['scope']) ? $filters['structure']['scope'] : '';
        $channel = $channelCode ? $this->channelRepo->findOneByIdentifier($channelCode) : null;
        $rootCategory = $channel && $channel->getCategory() ? $channel->getCategory() : null;
        $rootCategoryId = $rootCategory ? $rootCategory->getId() : null;
        
        $filteredCategories = !empty($this->getCategoriesFromFilter($filters['data'])) ?
                                $this->getCategoriesFromFilter($filters['data']) :
                                ($rootCategory ? [$rootCategory->getCode()] : []);
       
        if (count($filteredCategories) == 1 && $rootCategory->getCode() === reset($filteredCategories)) {
            if ($rootCategoryId) {
                $categories = $this->repository->findBy(
                    [ 'root' => $rootCategoryId ],
                    [ 'root' => 'ASC', 'left' => 'ASC' ]
                );
            } else {
                $categories = $this->repository->getOrderedAndSortedByTreeCategories();
            }
                
            foreach ($categories as $key => $category) {
                if ($rootCategoryId == $category->getId()) {
                    unset($categories[$key]);
                    break;
                }
            }
        } else {
            $categories = $this->repository->getCategoriesByCodes($filteredCategories);
            
            if ($categories instanceof ArrayCollection) {
                $categories = $categories->toArray();
            }
            
            $allCategory = $this->getSortedCategories($categories);
            
            $categories = [];
            foreach ($allCategory as $cat) {
                $categories[] = $cat;
            }
        }
        
        return new \ArrayIterator($categories);
    }

    public function getSortedCategories($categories)
    {
        $sortCategories = [];
        foreach ($categories as $category) {
            $sortCategories[] = ["level"=>$category->getLevel(),
                                "id"=>$category->getId(),
                                "code"=>$category->getCode()
                            ];
        }
        
        $sorter = array();
        foreach ($sortCategories as $key => $row) {
            $sorter[$key] = $row['level'];
        }

        array_multisort($sorter, SORT_ASC, $sortCategories);
       
        $categories = [];
        foreach ($sortCategories as $sortcategory) {
            $categoryCode = $this->repository->findOneBy(["code"=>$sortcategory['code']]);
            
            $categories[] = $categoryCode;
        }
        
        return $categories;
    }

    private function getCategoriesFromFilter($data)
    {
        $result = null;

        foreach ($data as $key => $value) {
            if (!empty($value['field']) && 'categories' == $value['field']) {
                $result = $value['value'];
            }
        }
        return $result;
    }
}
