<?php

namespace Drupal\drush\Commands;

use Drush\Commands\DrushCommands;

/**
 * A Drush command file.
 *
 * @package Drupal\drush\Commands
 */
class DrushCommand extends DrushCommands {
  /**
   * Drush command for swapi
   *
   * @param string $date
   * @command drush:import
   * @aliases import_nodes
   * @usage drush import_nodes $date
   */
  public function import($date = null) {
    /**
     * @var Drupal\swapi\Service\swapi
     */
    $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']);
      }
    }

    $count_update = 0;
    $count_create = 0;
    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) {
        $node = $swapi->getNodeFromUrl($item['url']);
        if ($node) {
          $swapi->update($item, $node);
          $count_update++;
        } else {
          $node = $swapi->createNode($item);
          $swapi->update($item, $node);
          $count_create++;
        }
      }
    }
    $this->output->writeln('Нод создано: ' . $count_create);
    $this->output->writeln('Нод обновлено: ' . $count_update);
  }
}
