<?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\TransportationFacilityAdapterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\TransportationFacility;
use Newland\Toubiz\Sync\Neos\Domain\Repository\TransportationFacilityRepository;

class TransportationFacilityImporter extends AbstractImporter
{
    /**
     * @Flow\Inject()
     * @var TransportationFacilityRepository
     */
    protected $transportationFacilityRepository;

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

        $facility = $this->transportationFacilityRepository->findOneByOriginalId($data->getExternalId());
        $persisted = (bool) $facility;

        if (!$facility) {
            $facility = new TransportationFacility;
        }

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

        $facility->setName($data->getName());
        $facility->setType($data->getType());
        $facility->setStatus($data->getStatus());
        $facility->setLength($data->getLength());
        $facility->setTravelTime($data->getTravelTime());
        $facility->setUpdatedAt($data->getUpdatedAt());

        if ($persisted) {
            $this->transportationFacilityRepository->update($facility);
        } else {
            $this->transportationFacilityRepository->add($facility);
        }

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