<?php

namespace Drupal\mymodule\Commands;

use Drush\Commands\DrushCommands;

/**
 * A Drush command file.
 *
 * @package Drupal\mymodule\Commands
 */
class BatchCommands extends DrushCommands {
  /**
   * Drush command that displays the given text.
   *
   * @param string $date
   * @command mymodule:custom
   * @aliases custom
   * @usage drush custom $date
   */
  public function custom($date = '01.01.1970') {
    $api = \Drupal::service('mymodule.custom_services');
    $result_api = $api->getResponse('https://swapi.dev/api');
    $queue_api = \Drupal::queue('mymodule_swapi_drush');
    $count_create_node = 0;
    $count_queue = 0;
    $queue_api->deleteQueue();

    foreach($result_api as $item) {
      $bundle = $api->getTypeNode($item);
      if ($api->checkBundle($bundle)) {
        $uri = $item;
        while (!empty($uri)) {
          $result = $api->getResponse($uri);
          foreach($result['results'] as $value) {
            $bundle = $api->getTypeNode($value['url']);
            $swapi_id = $api->getSwapiId($value['url']);
            $node = \Drupal::entityTypeManager()
              ->getStorage('node')
              ->loadByProperties([
                'type' => $bundle,
                'field_swapi_id' => $swapi_id,
              ]);
            foreach ($node as $val) {
              $node_edited = $val;
            }
            if (!empty($node)) {
              $swapi_edited = date_parse($value['edited']);
              $swapi_edited = $swapi_edited['day'] . "." . $swapi_edited['month'] . "." . $swapi_edited['year'];

              $swapi_edited = strtotime($swapi_edited);
              $date = strtotime($date);

              if ($date - $swapi_edited < 0) {
                $queue_api->createItem($value);
                $count_queue++;
              }
            } else {
              $api->createNode($value);
              $title = !empty($value['title']) ? $value['title'] : $value['name'];
              $this->output()->writeln("Страница $title создана");
              $count_create_node++;
              $queue_api->createItem($value);
            }
          }
          $uri = $result['next'];
        }
      } else {
        $this->output()->writeln("Content type $bundle не создан");
      }
    }

    while ($item = $queue_api->claimItem()) {
      if (!empty($item->data['url'])) {
        $node = $api->getNodeByUrl($item->data['url']);
        $api->edited($item->data, $node);

        $title = !empty($item->data['title']) ? $item->data['title'] : $item->data['name'];
        $message = "Страница $title обновлена";
        $this->output()->writeln($message);
        $queue_api->deleteItem($item);
      }
    }

    $this->output()->writeln("Страниц обновлено " . $count_queue . ", страниц создано " . $count_create_node);
  }
}
