<?php

namespace Drupal\mymodule\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use \Drupal\node\Entity\Node;
use \Drupal\Core\Cache\CacheableMetadata;

/**
 * Provides a resource to get people
 *
 * @RestResource(
 *   id = "get_people_node",
 *   label = @Translation("Get people"),
 *   uri_paths = {
 *     "canonical" = "/api/people/{id}",
 *   }
 * )
 */
class GetPeople extends ResourceBase {
  public function get($id) {

    if ($this->checkNode($id)) {
      $nodes = \Drupal::entityTypeManager()
        ->getStorage('node')
        ->loadByProperties([
          'type' => 'people',
          'field_swapi_id' => $id,
        ]);

      foreach ($nodes as $val) {
        $node = $val;
      }

      $response['name'] = $node->label();
      $response['height'] = $this->getFieldValue('field_height', $node);
      $response['mass'] = $this->getFieldValue('field_mass', $node);
      $response['hair_color'] = $this->getFieldValue('field_hair_color', $node);
      $response['skin_color'] = $this->getFieldValue('field_skin_color', $node);
      $response['eye_color'] = $this->getFieldValue('field_eye_color', $node);
      $response['birth_year'] = $this->getFieldValue('field_birth_year', $node);
      $response['gender'] = $this->getFieldValue('field_gender', $node);

      $node_homeworld = $node->field_homeworld->referencedEntities();
      $node_homeworld = $node_homeworld[0];
      $obj = [
        'id' => $node_homeworld->id(),
        'label' => $node_homeworld->label(),
      ];
      $response['homeworld'] = $obj;

      $response['films'][] = $this->fillReference('films', $node);
      $response['species'][] = $this->fillReference('species', $node);
      $response['vehicles'][] = $this->fillReference('vehicles', $node);
      $response['starships'] = $this->fillReference('starships', $node);

      $created = $node->get('created')->getValue();
      $created = date("Y-m-d H:i:s", (int)$created[0]['value']);
      $response['created'] = $created;

      $changed = $node->get('changed')->getValue();
      $changed = date("Y-m-d H:i:s", (int)$changed[0]['value']);
      $response['changed'] = $changed;

      $url = $node->toUrl()->setAbsolute()->toString(TRUE);
      $response['url'] = $url->getGeneratedUrl();

      $resource = new ResourceResponse($response, 200);
      return $resource;
    } else {
      $resource = new ResourceResponse('404 error', 404);
      return $resource;
    }
  }

  public function fillReference($nameAttr, $node) {
    $field_name = "field_" . $nameAttr;

    $items = $node->$field_name->referencedEntities();
    if (!empty($items)) {
      foreach ($items as $item) {
        $obj = [
          'id' => $item->id(),
          'label' => $item->label(),
        ];
        $result[$nameAttr][] = $obj;
      }
    } else {
      $result[$nameAttr][] = null;
    }
    return $result[$nameAttr];
  }

  public function getFieldValue($field_name, $node) {
    $value = $node->get($field_name)->getValue();
    $value = $value[0]['value'];
    return $value;
  }

  public function checkNode($swapi_id) {
    $nodes = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties([
        'type' => 'people',
        'field_swapi_id' => $swapi_id,
      ]);

    if (!empty($nodes)) {
      return true;
    }
    return false;
  }
}
