<?php

namespace Drupal\agaric_migration\Plugin\migrate\process;

use Drupal\Core\Database\Connection;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Update the redirect URIs with the correct ids.
 *
 * The nodes and users were migrated and in the new site they have new
 * ids, so we need to fix the uris before to pass them to the d7_path_redirect
 * plugin.
 *
 * @MigrateProcessPlugin(
 *   id = "migration_lookup_uri"
 * )
 */
class MigrationLookupUri extends ProcessPluginBase implements ContainerFactoryPluginInterface {

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $connection;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, Connection $database) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->connection = $database;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('database')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $redirect = $value[0];
    $new_value = [];
    // We just pass along the $redirect_options.
    $new_value[1] = $value[1];

    // The entities used in the old agaric sites are: user and node.
    if (preg_match('/^(user|node)\/([0-9]+)$/', $redirect, $matches)) {
      $entity_type = $matches[1];
      $id = $matches[2];

      if ($entity_type == 'node') {
        $node_migrations = [
          'migrate_map_agaric_blog',
          'migrate_map_agaric_page',
        ];
        foreach ($node_migrations as $node_migration) {
          $result = $this->connection->select($node_migration, 'm')
            ->fields('m')
            ->condition('sourceid1', $id)
            ->execute();
          $row = $result->fetchAssoc();
          if (!empty($row)) {
            $new_value[0] = 'node/' . $row['destid1'];
            break;
          }
          $new_value[0] = 'node/' . $row['destid1'];
        }
      }
      elseif ($entity_type == 'user') {
        $result = $this->connection->select('migrate_map_agaric_user', 'm')
          ->fields('m')
          ->condition('sourceid1', $id)
          ->execute();
        $row = $result->fetchAssoc();
        $id = (!empty($row)) ? $row['destid1'] : $id;
        $new_value[0] = 'user/' . $id;
      }
    }
    else {
      // Anything different that a redirect to user or node will be ignored.
      $new_value[0] = $value[0];
    }

    return $new_value;
  }

}
