<?php

namespace Drupal\popsu_migrate\Plugin\migrate\source;

use Drupal\migrate\Row;
use Drupal\migrate_drupal\Plugin\migrate\source\d7\FieldableEntity;

/**
 * Taxonomy term source from database.
 *
 * @MigrateSource(
 *   id = "d7_taxoterm_ville",
 *   source_module = "taxonomy"
 * )
 */
class D7TaxotermVille extends FieldableEntity {

  /**
   * {@inheritdoc}
   */
  public function query() {
    $query = $this->select('taxonomy_term_data', 'td')
      ->fields('td')
      ->orderBy('tid');

    $query->leftJoin('taxonomy_vocabulary', 'tv', 'td.vid = tv.vid');
    $query->addField('tv', 'machine_name');

    if (isset($this->configuration['bundle'])) {
      $query->condition('tv.machine_name', (array) $this->configuration['bundle'], 'IN');
    }

    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'tid' => $this->t('The term ID.'),
      'vid' => $this->t('Existing term VID'),
      'machine_name' => $this->t('Vocabulary machine name'),
      'name' => $this->t('The name of the term.'),
      'description' => $this->t('The term description.'),
      'weight' => $this->t('Weight'),
      'parent' => $this->t("The Drupal term IDs of the term's parents."),
      'format' => $this->t("Format of the term description."),
      'synonyms' => $this->t("Term's Synonyms (field : synonyms_synonym)"),
      'displayed_on_advanced_search' => $this->t("field_used_on_advanced_search"),
      'revision_id' => $this->t('Revision ID'),
      'language' => $this->t('Term translation language'),
      'source' => $this->t('Term translation source language'),
    ];
    return $fields;
  }


  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $language = $row->getSourceProperty('language');
    // drush_print('-- '.$language."\t".$row->getSourceProperty('tid')."\t".$row->getSourceProperty('name'));

    $tid = $row->getSourceProperty('tid');
    // vocabulary machine name
    $machine_name = $row->getSourceProperty('machine_name');
    $revid = $row->getSourceProperty('revision_id');

    // Get Field API field values.
    foreach ($this->getFields('taxonomy_term', $machine_name) as $field_name => $field) {
      $row->setSourceProperty($field_name, $this->getFieldValues('taxonomy_term', $field_name, $tid, $revid, NULL));
    }

    return parent::prepareRow($row);
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    $ids['tid']['type'] = 'integer';
    return $ids;
  }

}
