<?php

namespace Drupal\geo_upgrade\Plugin\migrate\source;

use Drupal\migrate\Plugin\migrate\source\SqlBase;
use Drupal\migrate\Row;

/**
 * Drupal 7 node source from database.
 *
 * @MigrateSource(
 *   id = "geod7_author",
 *   source_module = "geo_upgrade"
 * )
 */
class Author extends SqlBase {


  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $field_author = $row->getSourceProperty('field_author_value');
    // Make sure to all the author names are trimmed.
    $row->setSourceProperty('field_author_value', trim($field_author));

    // The bio value is going to be get from the last contribution of the user
    // where the bio field is not empty.
    $query = $this->database->query(
      'SELECT
                fdfa.entity_id,
                fdfa.revision_id,
                n.nid
            FROM field_data_field_author fdfa
            LEFT JOIN node n ON (n.nid = fdfa.entity_id)
            WHERE field_author_value = :field_author
            ORDER BY entity_id DESC',
      ['field_author' => $field_author]
    );
    foreach ($query as $record) {
      $row->setSourceProperty('uid', $record->uid);
      $bio_query = $this->database->query(
        "SELECT field_author_bio_value FROM field_data_field_author_bio WHERE entity_id = :entity_id AND revision_id = :revision_id",
        ['entity_id' => $record->entity_id, 'revision_id' => $record->revision_id]
      );
      $bio_result = $bio_query->fetchAssoc();

      // Once we find a bio no need to continue.
      if (!empty($bio_result)) {
        break;
      }
    }

    $row->setSourceProperty('bio', ["value" => '']);
    if (!empty($bio_result)) {
      $row->setSourceProperty('bio', ["value" => $bio_result['field_author_bio_value']]);
    }

    return parent::prepareRow($row);
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'field_author_value' => $this->t('Author Name'),
    ];
    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    $ids['field_author_value']['type'] = 'string';
    $ids['field_author_value']['alias'] = 'fdfa';

    return $ids;
  }

  /**
   * {@inheritdoc}
   */
  public function query() {
    $select = $this->select('field_data_field_author', 'fdfa')
      ->fields('fdfa', [
        'field_author_value',
      ])
    ->groupBy('field_author_value');

    return $select;
  }

}
