<?php

namespace FR\V1_0\Entities\RemoteHub;

use FR\Interfaces\RemoteHubInterface;
use FR\V1_0\Entities\Transports\TransportEntityFactory;

/**
 * Class CreateRemoteHubEntityService
 * @package FR\V1_0\Services
 */
class CreateRemoteHubEntity implements \FR\Interfaces\CreateRemoteHubEntityInterface
{
    /**
     * @param \stdClass $data
     *
     * @return RemoteHubInterface
     */
    public static function createFromStdClass(\stdClass $data): RemoteHubInterface
    {
        $transportMode = isset($data->transport->mode) && !empty($data->transport->mode) ? $data->transport->mode : '';
        $transportEntity = TransportEntityFactory::create($transportMode);
        $transportEntity->fromArray((array) $data->transport);
        $transportEntity->validate();

        $remoteHubEntity = new RemoteHub();
        $remoteHubEntity->fromArray((array)$data);
        $remoteHubEntity->setTransport($transportEntity);
        $remoteHubEntity->validate();

        return $remoteHubEntity;
    }

    public static function createFromDbResult(array $data): RemoteHubInterface
    {
        $data['transport'] = json_decode($data['transport'], JSON_OBJECT_AS_ARRAY);
        $transportMode = isset($data['transport']['mode']) && !empty($data['transport']['mode']) ? $data['transport']['mode'] : '';
        $transportEntity = TransportEntityFactory::create($transportMode);
        $transportEntity->fromArray($data['transport']);
        $transportEntity->validate();

        $remoteHubEntity = new RemoteHub();
        $remoteHubEntity->fromArray($data);
        $remoteHubEntity->setTransport($transportEntity);
        $remoteHubEntity->validate();

        return $remoteHubEntity;
    }
}
