<?php

namespace Drupal\edlp_migrate\Plugin\migrate\source;

use Drupal\Core\Database\Database;
use Drupal\migrate\Row;
use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase;

/**
 * D6 Edlp Taxonomy Entree term source from database.
 *
 * @MigrateSource(
 *   id = "d6_edlp_taxonomy_term_entree"
 * )
 */
class D6EdlpTaxonomyTermEntree extends DrupalSqlBase {

  /**
   * {@inheritdoc}
   */
  public function query() {
    // drush_print('D6EdlpTaxonomyTermEntree query');

    $query = $this->select('term_data', 'td')
      ->fields('td')
      ->distinct()
      ->orderBy('td.tid');

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

    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'tid' => $this->t('The term ID.'),
      'vid' => $this->t('Existing term VID'),
      '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."),
      'node_nid' => $this->t("The node's nid of entree's description."),
    ];
    if (isset($this->configuration['translations'])) {
      $fields['language'] = $this->t('The term language.');
      $fields['trid'] = $this->t('Translation ID.');
    }
    // print_r($fields);
    // print_r("\n");

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    // drush_print_r($row);
    // Find parents for this row.
    $parents = $this->select('term_hierarchy', 'th')
      ->fields('th', ['parent', 'tid'])
      ->condition('tid', $row->getSourceProperty('tid'))
      ->execute()
      ->fetchCol();
    $row->setSourceProperty('parent', $parents);

    // find node attached to this term for description
    $query = $this->select('content_type_entree', 'cte');
    // $query->fields('cte', ['nid', 'vid', 'field_entree_value']);
    $query->condition('cte.field_entree_value', $row->getSourceProperty('tid'));
    $query->join('node_revisions', 'nr', 'cte.nid = nr.nid');
    $query->addField('nr', 'body');
    $description = $query->execute()
      ->fetchField();
    // drush_print_r($node);
    // empty enties to keep migrate
    $empty_entries = array(267, 291, 309, 310);

    if($description == "" && in_array($row->getSourceProperty('tid'), $empty_entries)){
      $description = "a remplir";
    }

    $row->setSourceProperty('description', $description);

    // get the node type page:notice from source and add it to notice field
    // find node attached to this term for description
    // get all notice
    $query = $this->select('term_node', 'tn');
    $query->condition('tn.tid', 8 ); // page type notice tid
    $query->addField('tn', 'nid');
    $notices_nids = $query->execute()->fetchCol();

    // get all nodes taged with the current entree
    $query = $this->select('term_node', 'tn');
    $query->condition('tn.tid', $row->getSourceProperty('tid'));
    $query->addField('tn', 'nid');
    $nodes_nids = $query->execute()->fetchCol();

    $notice_nid = array_shift(array_intersect($notices_nids, $nodes_nids));
    // drush_print('notice_nid : ', 0, null, false);
    // drush_print_r($notice_nid);
    $query = $this->select('node_revisions', 'nr');
    $query->condition('nr.nid', $notice_nid ); // page type notice tid
    $query->addField('nr', 'body');
    $notices_body = $query->execute()->fetchField();
    // drush_print('notices_body : ', 0, null, false);
    // drush_print_r($notices_body);

    // convert inner text links to internal nodes to new url
    preg_match_all('/href="(\/?corpus\/[^"]+)"/', $notices_body, $links);
    // drush_print('links : ', 0, null, false);
    // drush_print_r($links);
    foreach ($links[1] as $key => $path) {
      $path = preg_replace('/^\//', '', $path);
      // drush_print('path : ', 0, null, false);
      // drush_print_r($path);

      // find the source path
      $query = $this->select('url_alias', 'ua');
      $query->condition('dst', $path);
      $query->addField('ua', 'src');
      $src = $query->execute()->fetchField();
      // drush_print('src : ', 0, null, false);
      // drush_print_r($src);
      if($src){
        // get the nid
        $nid = str_replace('node/', '', $src);
        // drush_print('nid : ', 0, null, false);
        // drush_print_r($nid);
        // find the new nid of the enregistrement (corpus item) from migration map
        // get the d6_edlp_migration
        // drush_print_r($this->migration->getIdMap()->lookupDestinationId(array($nid)));
        $new_nid = Database::getConnection('default', 'default')
          ->select('migrate_map_d6_edlp_corpus', 'm')
          ->fields('m', ['destid1'])
          ->condition('sourceid1', $nid)
          ->execute()
          ->fetchField();
        // drush_print('new_nid : ', 0, null, false);
        // drush_print_r($new_nid);
        if($new_nid){
          $notices_body = str_replace($path, "node/".$new_nid, $notices_body);
        }
      }else{
        drush_print('no source for path : ', 0, null, false);
        drush_print_r($path);
      }

    }

    $row->setSourceProperty('notice', $notices_body);

    return parent::prepareRow($row);
  }

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

}
