<?php

namespace Drupal\swapi\Service;

use GuzzleHttp\ClientInterface;

class swapi {
  private $http_client;
  private $url;
  private $queue;

  public function __construct(ClientInterface $http_client) {
    $this->http_client = $http_client;
    $this->url = 'https://swapi.dev/api/';
    $this->queue = \Drupal::queue('swapi');
    $this->queue->createQueue();
  }

  public function getResponse() {
    $response = $this->http_client->request('GET', $this->url);
    $response = json_decode($response->getBody()->getContents(), TRUE);
    return $response;
  }

  public function setUrl($url) {
    $this->url = $url;
    return $this;
  }

  public function getUrl() {
    return $this->url;
  }

  public function addQueue($items, $gmt_time_cron) {
    $queue = $this->queue;
    foreach ($items as $item) {
      $node = $this->getNodeFromUrl($item['url']);

      if ($node) {
        if ($node->isPublished()) {
          $gmp_time_update_node = $node->getChangedTime();
          if ($gmp_time_update_node > $gmt_time_cron) {
            $queue->createItem($item);
          }
        } else {
          $queue->createItem($item);
        }
      } else {
        $this->createNode($item);
        $queue->createItem($item);
      }
    }
  }

  public function getNodeFromUrl($url) {
    $bundle = $this->getBundle($url);
    $swapi_id = $this->getSwapiId($url);
    $nodes = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties([
        'type' => $bundle,
        'field_swapi_id' => $swapi_id,
      ]);

    return !empty($nodes) ? current($nodes) : null;
  }

  public function update($data, $node) {
    $title = $data[array_keys($data)[0]];
    $node->setTitle($title);
    foreach ($data as $key => $value) {
      $field_name = "field_" . strtolower($key);
      unset($node_add);
      if ($node->hasField($field_name) and isset($value)) {
        if (is_array($value)) {
          foreach ($value as $url) {
            $node_add[] = $this->getNodeFromUrl($url);
          }
          $node->set($field_name, $node_add);
          continue;
        }
        if ($key == 'homeworld') {
          $node_add = $this->getNodeFromUrl($value);
          $node->set($field_name, $node_add);
          continue;
        }
        $node->set($field_name, $value);
      }
    }
    $node->setPublished();
    $node->save();
  }

  public function createNode($item) {
    $title = $item[array_keys($item)[0]];
    $bundle = $this->getBundle($item['url']);
    $swapi_id = $this->getSwapiId($item['url']);

    $node = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->create([
        'type' => $bundle,
        'title' => $title,
        'field_swapi_id' => $swapi_id
      ]);
    $node->setUnpublished();
    $node->save();
    return $node;
  }

  public function getSwapiId($url) {
    $swapi_id = explode('/', stristr($url, 'api/'));
    return $swapi_id[2];
  }

  public function getBundle($url) {
    $type_node = explode('/', stristr($url, 'api/'));
    return $type_node[1];
  }
}
