<?php

namespace Drupal\mymodule\Plugin\QueueWorker;

use Drupal\Core\Queue\QueueWorkerBase;

/**
 * Comments
 *
 * @QueueWorker (
 *  id = "mymodule_swapi",
 *  title = "Queue swapi",
 *  cron = {"time" = 60}
 * )
 */
class QueueSwapi extends QueueWorkerBase {

  public function processItem($data) {
    $node = $this->getNodeByUrl($data['url']);

    $this->edited($data, $node);
  }

  private function edited($data, $node) {
    foreach ($data as $key => $value) {
      $field_name = "field_" . $key;
      $bool = (bool)($key != 'name' and $key != 'title' and $key != 'homeworld' and $key != 'url' and $key != 'created' and $key != 'people_exclude');
      if ($bool and !is_array($value)) {
        !empty($value) ? $node->set("field_" . strtolower($key), $value) : '';
      }
      if (is_array($value)) {
        foreach ($value as $item) {
          $nodeAdd = $this->getNodeByUrl($item);
          $node->set($field_name, NULL);
          !empty($nodeAdd) ? $node->$field_name[] = $nodeAdd : '';
        }
      }
      if ($key == 'homeworld' and !empty($value)) {
        $node->$field_name= $this->getNodeByUrl($value);
      }
      if ($key == 'name' or $key == 'title') {
        $node->setTitle($value);
      }
    }
    $node->save();
  }

  private function getNodeByUrl($uri) {
    $api = \Drupal::service('mymodule.custom_services');
    $bundle = $api->getTypeNode($uri);
    $swapi_id = $api->getSwapiId($uri);
    $nodes = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties([
        'type' => $bundle,
        'field_swapi_id' => $swapi_id,
      ]);

    foreach ($nodes as $value) {
      $node = $value;
    }
    return $node;
  }
}
