<?php

namespace Drupal\mymodule\Batch;

class Import {
  public $batch;
  public $operations;

  public function __construct() {
    $this->batch = [
      'title' => 'Import nodes',
    ];
  }

  public function getNodes($time = '01.01.1970') {
    $api = \Drupal::service('mymodule.custom_services');
    $result_api = $api->getResponse('https://swapi.dev/api');
    $this->operations = [];

    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) {
            $node = $api->getNodeByUrl($value['url']);
            if (!empty($node)) {
              $swapi_edited = date_parse($value['edited']);
              $swapi_edited = $swapi_edited['day'] . "." . $swapi_edited['month'] . "." . $swapi_edited['year'] . " " . $swapi_edited['hour'] . $swapi_edited['minute'] . $swapi_edited['second'];
              $swapi_edited = strtotime($swapi_edited);
              $time = strtotime($time);

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

  public function processItem($data) {
    $api = \Drupal::service('mymodule.custom_services');
    $node = $api->getNodeByUrl($data['url']);
    $api->edited($data, $node);
  }

  public function setOperation($data) {
    $this->batch['operations'][] = [[$this, 'processItem'], $data];
  }

  public function setBatch() {
    batch_set($this->batch);
  }

  public function processBatch() {
    batch_process();
  }

  public function finished($success, $results, $operations) {
    $a = 1;
    if ($success) {
      $message = \Drupal::translation()
        ->formatPlural(count($results), 'One post processed.', '@count posts processed.');
    }
    else {
      $message = t('Finished with an error.');
    }
    // ВЫВЕСТИ $message
  }
}
