<?php

declare(strict_types=1);

namespace Drupal\visitors\Form;

use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;

/**
 * Upgrade form.
 *
 * From 8.x-2.x to 3.0.x.
 */
final class UpgradeForm extends ConfirmFormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId(): string {
    return 'visitors_upgrade';
  }

  /**
   * {@inheritdoc}
   */
  public function getQuestion(): TranslatableMarkup {
    return $this->t('Migrate Visitors 8.x-2.x to 3.0.x');
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription(): TranslatableMarkup {
    return $this->t('This action will upgrade the data.');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl(): Url {
    return new Url('visitors.settings');
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    $operations = [
      [['\Drupal\visitors\Form\UpgradeForm', 'upgrade'], []],
    ];
    $batch = [
      'title' => $this->t('Upgrading data'),
      'operations' => $operations,
      'finished' => '\Drupal\visitors\Form\UpgradeForm::finished',
    ];
    if (function_exists('batch_set')) {
      \batch_set($batch);
    }

    return 1;
  }

  /**
   * Batch method for upgrading.
   *
   * @param array $context
   *   The batch context.
   */
  public static function upgrade(&$context) {

    $service = \Drupal::service('visitors.upgrade');
    if (!isset($context['sandbox']['max'])) {
      $context['sandbox']['max'] = $service->getTotal();
      $context['sandbox']['current'] = 0;
      $context['finished'] = ($context['sandbox']['max'] == $context['sandbox']['current']) ? 1 : $context['sandbox']['current'] / $context['sandbox']['max'];

      return;
    }

    $batch_size = 50;
    $rows = $service->getVisitorsRows($batch_size);

    foreach ($rows as $row) {
      $service->upgradeRow((array) $row);
      $context['sandbox']['current'] += 1;
    }

    $context['finished'] = ($context['sandbox']['max'] == $context['sandbox']['current']) ? 1 : $context['sandbox']['current'] / $context['sandbox']['max'];
  }

}
