<?php

namespace Webkul\DamBundle\Extension;

use Webkul\DamBundle\Repository\AssetRepository;
use Doctrine\ORM\EntityManager;
use Webkul\DamBundle\Entity\Asset;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class MassDeleteController
{
    /** @var assetRepository */
    protected $assetRepository;

    /** @var EntityManager */
    protected $em;

    /**
     * @param CategoryRepositoryInterface $repository
     * @param NormalizerInterface         $normalizer
     * @param ObjectFilterInterface       $objectFilter
     */
    public function __construct(
        $assetRepository,
        EntityManager $em
    ) {
        $this->assetRepository = $assetRepository;
        $this->em = $em;
    }

    public function massDeleteAction(Request $request)
    {
        $data = json_decode($request->getContent(), true);
        $values = explode(",", $data['values']);
        $starred = null;
        $tagCode = null;
        $code = null;
        foreach ($data as $key => $value) {
            if(strpos($key, 'filters') !== false) {
                if($key == 'filters[starred][value]') {
                    $starred = $value;
                } elseif($key == 'filters[code][value]') {
                    $code = $value;
                }
            }
        }

        $filters = [
            "starred" => $starred,
            "tagcode" => $tagCode,
            "code" => $code
        ];
        
        if (count($values) == $data['itemsCount']) {
            try {
                if (!($this->assetRepository->deleteFromIds($values))) {
                    throw new \Exception("Error Processing Request", 1);
                }
            } catch (\Exception $e) {
                return new Response('false', Response::HTTP_BAD_REQUEST);
            }
        } else {
            try {
                if (!($this->assetRepository->deleteFromNotInIds($values, $filters))) {
                    throw new \Exception("Error Processing Request", 1);
                }
            } catch (\Exception $e) {
                return new Response('false', Response::HTTP_BAD_REQUEST);
            }
        }

        return new Response('true', Response::HTTP_OK);
    }
}
