<?php

namespace Drupal\mymodule;

use GuzzleHttp\ClientInterface;

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();

    $response = $request->getBody()->getContents();
    $response = json_decode($response, true);

    return $response;
  }

  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);
  }

}
