<?php

namespace Webkul\DamBundle\Controller;

use Webkul\DamBundle\Repository\AssetCategoryRepository;
use Webkul\DamBundle\Repository\AssetRepository;
use Doctrine\Common\Collections\Collection;
use Oro\Bundle\SecurityBundle\SecurityFacade;
use Pim\Component\Catalog\Model\CategoryInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Doctrine\Common\Collections\ArrayCollection;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;

$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
 * Controller used to render categories of an entity (like assets).
 *
 * @author    Aman Srivastava <aman.srivastava462@webkul.com>
 * @copyright 2018 Webkul Soft. Pvt. Ltd. (http://www.webkul.com)
 */
class AssetCategoryListController extends Controller
{
    /** @var AssetRepository */
    protected $productRepository;

    /** @var AssetsCategoryRepository */
    protected $categoryRepository;

    /** @var SecurityFacade */
    protected $securityFacade;

    /** @var string */
    protected $categoryClass;

    /** @var string */
    protected $acl;

    /** @var string */
    protected $template;

    /** @var UserContext */
    protected $userContext;
    /**
     * @param AssetsCategoryRepository $categoryRepository
     * @param SecurityFacade              $securityFacade
     * @param string                      $categoryClass
     * @param string                      $acl
     * @param string                      $template
     */
    public function __construct(
        \BaseUserContext $userContext,
        AssetRepository $productRepository,
        AssetCategoryRepository $categoryRepository,
        string $categoryClass,
        SecurityFacade $securityFacade,
        string $acl,
        string $template
    ) {
        $this->userContext        =   $userContext;
        $this->productRepository  =   $productRepository;
        $this->categoryRepository =   $categoryRepository;
        $this->categoryClass      =   $categoryClass;
        $this->securityFacade     =   $securityFacade;
        $this->acl                =   $acl;
        $this->template           =   $template;
    }

    /**
     * List categories associated with the provided product and descending from the category
     * defined by the parent parameter.
     *
     * @param Request    $request    The request object
     * @param string     $id         Product id
     * @param int        $categoryId The parent category id
     *
     * httpparam include_category if true, will include the parentCategory in the response
     *
     * @return Response
     */
    public function listCategoriesAction(Request $request, $id, $categoryId)
    {
        $entityWithCategories = $this->findEntityWithCategoriesOr404($id);
        $category = $this->categoryRepository->find($categoryId);
        $category->setLocale($this->userContext->getCurrentLocaleCode());
        
      
        if (null === $category) {
            throw new NotFoundHttpException(sprintf('%s category not found', $this->categoryClass));
        }

        $categories = null;
        $selectedCategoryIds = $request->get('selected', null);
        
        if (null !== $selectedCategoryIds) {
            $categories = $this->categoryRepository->getCategoriesByIds($selectedCategoryIds);

            foreach ($categories as $res) {
                $res->setLocale($this->userContext->getCurrentLocaleCode());
            }
            $categories = new ArrayCollection($categories);
        } elseif (null !== $entityWithCategories) {
            $categories = $entityWithCategories->getCategories();
        }
       
        $trees = $this->getFilledTree($category, $categories);
        
        return $this->render($this->template, ['trees' => $trees, 'categories' => $categories]);
    }

    /**
     * Find an entity by its id or return a 404 response
     *
     * @param string $id
     *
     * @return mixed
     *
     * @throws NotFoundHttpException
     */
    protected function findEntityWithCategoriesOr404(string $id)
    {
        $product = $this->productRepository->find($id);
        if (null === $product) {
            throw new NotFoundHttpException(
                sprintf('Product with with ID "%s" could not be found.', $id)
            );
        }
        // With this version of the form we need to add missing values from family
        // $this->valuesFiller->fillMissingValues($product);
        // $this->productBuilder->addMissingAssociations($product);

        return $product;
    }

    /**
     * Fetch the filled tree
     *
     * @param CategoryInterface $parent
     * @param Collection        $categories
     *
     * @return CategoryInterface[]
     */
    protected function getFilledTree($parent, Collection $categories): array
    {
        $categoryies = $this->categoryRepository->getFilledTree($parent, $categories);
        foreach ($categoryies as $category) {
            $category->setlocale($this->userContext->getCurrentLocaleCode());
        }

        return $this->categoryRepository->buildTreeNode($categoryies);
    }
}
