<?php

namespace Drupal\batch\Batch;

class ImportSwapi {
  private $batch;
  const STEP = 1;

  public function __construct($title = 'Nodes import') {
    $this->batch = [
      'title' => $title
    ];
  }

  public function getOperations($date = null) {
    $swapi = \Drupal::service('swapi.service_swapi');
    $date = strtotime($date);

    $urls = $swapi->getResponse();
    $items = [];
    foreach ($urls as $url) {
      $result = $swapi->setUrl($url)
                      ->getResponse();
      $items = array_merge($items, $result['results']);
      while ($result['next']) {
        $result = $swapi->setUrl($result['next'])
                        ->getResponse();
        $items = array_merge($items, $result['results']);
      }
    }

    foreach ($items as $item) {
      $swapi_edited = date_parse($item['edited']);
      $swapi_edited = $swapi_edited['day'] . "." . $swapi_edited['month'] . "." . $swapi_edited['year'];
      $swapi_edited = strtotime($swapi_edited);
      if ($swapi_edited > $date) {
        $this->setOperation([$item]);
      }
    }
  }

  public function processItem($data) {
    $swapi = \Drupal::service('swapi.service_swapi');
    if (!empty($data['url'])) {
      $node = $swapi->getNodeFromUrl($data['url']);
      if ($node) {
        $swapi->update($data, $node);
      } else {
        $node = $swapi->createNode($data);
        $swapi->update($data, $node);
      }
    }
  }

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

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