<?php

namespace Drupal\mymodule;

use GuzzleHttp\ClientInterface;
use Drupal\Core\Datetime\DrupalDateTime;

class API {
  protected $httpClient;

  public function __construct(ClientInterface $httpClient) {
    $this->httpClient = $httpClient;
  }

  public function getResponse($uri) {
    $request = $this->httpClient->request('GET', $uri);
    $responseCode = $request->getStatusCode();

    #if ($responseCode == 200) {
      $response = $request->getBody()->getContents();
      $response = json_decode($response, true);
      return $response;
    #}
    #return false;
  }

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

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

  public function checkBundle($bundle) {
    $bundles = \Drupal::getContainer()->get('entity_type.bundle.info')->getBundleInfo('node');
    foreach ($bundles as $key => $value) {
      if ($key == $bundle) {
        return true;
      }
    }
    return false;
  }

  public function createNode($item) {
    $queue_api = \Drupal::queue('mymodule_swapi');
    $bundle = $this->getTypeNode($item['url']);
    $swapi_id = (int)$this->getSwapiId($item['url']);
    $title = $item[array_keys($item)[0]];

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

  public function getNodeByUrl($uri) {
    $bundle = $this->getTypeNode($uri);
    $swapi_id = $this->getSwapiId($uri);
    $nodes = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties([
        'type' => $bundle,
        'field_swapi_id' => $swapi_id,
      ]);
    foreach ($nodes as $value) {
      $node = $value;
    }
    return $node;
  }

  public 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)) {
        isset($value) ? $node->set("field_" . strtolower($key), $value) : '';
      }
      if (is_array($value)) {
        $node->set($field_name, NULL);
        foreach ($value as $item) {
          $nodeAdd = $this->getNodeByUrl($item);
          !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();
  }
}
