<?php

namespace Webapp\Core\ApiOperation;

use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\HttpFoundation\Request;
use Webapp\Core\Entity\ValueList;
use Webapp\Core\Entity\ValueListItem;

/**
 * Class DeleteBusinessObjectOperation.
 */
final class UpdateValueListOperation
{


    /**
     * @param Request $request
     * @param ValueList $data
     * @return mixed
     */
    public function __invoke(Request $request, ValueList $data)
    {
        $variable = $data->getVariable();
        while($variable->getGeneratorVariable() !== null){
            $variable = $variable->getGeneratorVariable();
        }
        $project = $variable->getProjectData()->getProject();
        foreach ($project->getSimpleVariables() as $simpleVariable){
            if (
                $simpleVariable->getName() === $data->getVariable()->getName() &&
                !!$simpleVariable->getValueList() &&
                $simpleVariable->getValueList()->getName() === $data->getName()
            ){
                $this->updateValueList($simpleVariable->getValueList(), $data);
            }
        }
        foreach ($project->getPlatform()->getSite()->getValueLists() as $valueList){
            if (
                $valueList->getName() === $data->getName()
            ){
                $this->updateValueList($valueList, $data);
            }
        }
        return $data;
    }

    /**
     * @param $valueList
     * @param ValueList $data
     * @return void
     */
    private function updateValueList($valueList, ValueList $data): void
    {
        $valueList->setValues(new ArrayCollection());
        foreach ($data->getValues() as $value) {
            $valueList->addValue(new ValueListItem($value->getName()));
        }
    }

}
