<?php
namespace Webkul\DamBundle\Controller;

use Oro\Bundle\SecurityBundle\Annotation\AclAncestor;
use Pim\Component\Catalog\Model\ProductInterface;
use Webkul\DamBundle\Repository\AssetCategoryRepository;
use Webkul\DamBundle\Repository\AssetRepository;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;

$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
 * Asset category controller
 *
 * @author    Aman Srivastava <aman.srivastava462@webkul.com>
 * @copyright 2019 Webkul Software Pvt. Ltd (http://www.webkul.com)
 */
class AssetCategoryController
{
    /** @var AssetRepository */
    protected $assetRepository;

    /** @var AssetCategoryRepository*/
    protected $assetCategoryRepository;

    /** @var ObjectFilterInterface */
    protected $objectFilter;

    /** @var UserContext */
    protected $userContext;

    /**
     * @param AssetRepository         $productRepository
     * @param AssetCategoryRepository $productCategoryRepository
     * @param ObjectFilterInterface              $objectFilter
     */
    public function __construct(
        AssetRepository $productRepository,
        AssetCategoryRepository $productCategoryRepository,
        \ObjectFilterInterface $objectFilter,
        \BaseUserContext $userContext
    ) {
        $this->productRepository         = $productRepository;
        $this->productCategoryRepository = $productCategoryRepository;
        $this->objectFilter              = $objectFilter;
        $this->userContext               = $userContext;
    }

    /**
     * List categories and trees for a product
     *
     * @param string $id
     *
     * @AclAncestor("webkul_dam_configuration")
     *
     * @return JsonResponse
     */
    public function listAction($id)
    {
        $product = $this->findProductOr404($id);
        
        $trees = $this->productCategoryRepository->getItemCountByTrees($product);
        $alltree = [];
        foreach ($trees as $tree) {
            $tree['tree']->setLocale($this->userContext->getCurrentLocaleCode());
            $alltree[] = $tree;
        }
        
        $result['trees'] = $this->buildTrees($trees);
        $result['categories'] = $this->buildCategories($product);
        
        return new JsonResponse($result);
    }

    /**
     * Find a product by its id or return a 404 response
     *
     * @param string $id the product id
     *
     * @throws NotFoundHttpException
     *
     * @return ProductInterface
     */
    protected function findProductOr404($id)
    {
        $product = $this->productRepository->find($id);

        if (!$product) {
            throw new NotFoundHttpException(
                sprintf('Product with id %s could not be found.', (string) $id)
            );
        }

        return $product;
    }

    /**
     * @param array $trees
     *
     * @return array
     */
    protected function buildTrees(array $trees)
    {
        $result = [];

        foreach ($trees as $tree) {
            $category = $tree['tree'];

            if (!$this->objectFilter->filterObject($category, 'pim.internal_api.product_category.view')) {
                $result[] = [
                    'id'         => $category->getId(),
                    'code'       => $category->getCode(),
                    'label'      => $category->getLabel(),
                    'associated' => $tree['itemCount'] > 0
                ];
            }
        }

        return $result;
    }

    /**
     * @param ProductInterface $product
     *
     * @return array
     */
    protected function buildCategories($product)
    {
        $result = [];

        foreach ($product->getCategory() as $category) {
            $result[] = [
                'id'     => $category->getId(),
                'code'   => $category->getCode(),
                'rootId' => $category->getRoot(),
            ];
        }

        return $result;
    }
}
