<?php
namespace Newland\Toubiz\Sync\Neos\Importer;

/*
 * This file is part of the "toubiz-sync-neos" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Neos\Flow\Annotations as Flow;
use Newland\Toubiz\Api\ObjectAdapter\SlopeAdapterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\Slope;
use Newland\Toubiz\Sync\Neos\Domain\Repository\SlopeRepository;

class SlopeImporter extends AbstractImporter
{
    /**
     * @Flow\Inject()
     * @var SlopeRepository
     */
    protected $slopeRepository;

    /**
     * Import method.
     *
     * Persist given data by creating new objects or updating existing ones.
     *
     * @param SlopeAdapterInterface $data
     * @return Slope|null
     */
    public function import($data)
    {
        $this->initializeLogger($data, [
            'slope' => [
                'externalId' => $data->getExternalId(),
                'name' => $data->getName(),
            ]
        ]);

        $slope = $this->slopeRepository->findOneByOriginalId($data->getExternalId());
        $persisted = (bool) $slope;

        if (!$slope) {
            $slope = new Slope();
        }

        if (!$slope->getOriginalId()) {
            $slope->setOriginalId($data->getExternalId());
        }

        $slope->setName($data->getName());
        $slope->setType($data->getType());
        $slope->setStatus($data->getStatus());
        $slope->setDifficulty($data->getDifficulty());
        $slope->setUpdatedAt($data->getUpdatedAt());

        if ($persisted) {
            $this->slopeRepository->update($slope);
        } else {
            $this->slopeRepository->add($slope);
        }

        $this->persistenceManager->persistAll();
        return $slope;
    }
}
