<?php

namespace Diamond\Modules\AdminContents;

use ActiveTable\Contracts\CommandInterface;
use ActiveTable\DataTableEngine;
use Diamond\Domain\ContentTag\Contracts\ContentTagRepositoryInterface;
use Diamond\Infrastructure\Models\Content\Content;
use Diamond\Infrastructure\Models\ContentTag\ContentTag;
use Diamond\Infrastructure\Models\ContentTag\ContentTagQuery;
use Diamond\Infrastructure\Models\ContentTagRel\ContentTagRel;
use Diamond\Infrastructure\Models\ContentTagRel\ContentTagRelQuery;
use Diamond\Repositories\Content\ContentRepository;
use DiamondTable\CommandException;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\Collection\Collection;
use Propel\Runtime\Exception\PropelException;
use Diamond\Helpers\Form;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class SaveContentCommand
 * @package Diamond\Modules\AdminContents
 */
class SaveContentCommand implements CommandInterface
{
    /**
     * @var DataTableEngine
     */
    protected $tableEngine;

    /**
     * @var ContentRepository
     */
    protected $repo;

    /**
     * SaveContentCommand constructor.
     * @param DataTableEngine $tableEngine
     */
    public function __construct(DataTableEngine $tableEngine)
    {
        $this->tableEngine = $tableEngine;
        $this->repo = $this->tableEngine->getRepo();
    }


    public function process(): void
    {
        $request = Request::createFromGlobals();

        //некоторые данные в post перелпределяются, например загрузка картинок
        $ids = $request->request->get('ids');
        $tags = $request->request->get('tags')??[];
        $id  = $request->request->get('id');

        $data = $request->request->all();
        unset($data['id']);

        array_walk($data,function (&$el){
            $el = $el!=='NULL' ? $el : null;
        });

        /**
         * @var Content $entity
         */

        if ($id) {
            $entity = $this->repo->buildEntityFromArray($data, $this->repo->findById($id));
        }
        //update
        else {
            $entity = $this->repo->buildEntityFromArray($data);
        }

        $entity->getContentTagRels()->delete();

        $collection = new Collection();

        if(count($tags)){
            foreach ($tags as $tag){
                $tagRel = (new ContentTagRel())->setContentTagId($tag)->setContentId($id);
                $collection->push($tagRel);
            }
        }

        $entity->setContentTagRels($collection);

        try {
            $this->repo->save($entity);
        } catch (PropelException $ex) {
            throw new CommandException($ex->getMessage());
        }

        Form::addTableNotice(
            Form::buildSuccessMessage(
                'Запись №' . $entity->getId() . ' успешно сохранена! ' . anchor(adaptive_url([]), 'Добавить новую запись')
            )
        );

        RedirectResponse::create(adaptive_url([], ['fn', 'id']))->send();
    }

}