<?php

namespace Drupal\edlp_migrate\Plugin\migrate\source;

use Drupal\Core\Database\Database;
use Drupal\migrate\Row;
use Drupal\node\Plugin\migrate\source\d6\Node as D6Node;

/**
 * Source plugin for edlp corpus migration.
 *
 * @MigrateSource(
 *   id = "d6_edlp_pages"
 * )
 */
class D6EdlpPages extends D6Node {


  /**
   * {@inheritdoc}
   */
  public function query() {
    $query = $this->select('node_revisions', 'nr');
    $query->innerJoin('node', 'n', static::JOIN);
    $this->handleTranslations($query);

    $query->fields('n', [
        'nid',
        'type',
        'language',
        'status',
        'created',
        'changed',
        'comment',
        'promote',
        'moderate',
        'sticky',
        'tnid',
        'translate',
      ])
      ->fields('nr', [
        'title',
        'body',
        'teaser',
        'log',
        'timestamp',
        'format',
        'vid',
      ]);
    $query->addField('n', 'uid', 'node_uid');
    $query->addField('nr', 'uid', 'revision_uid');

    // If the content_translation module is enabled, get the source langcode
    // to fill the content_translation_source field.
    if ($this->moduleHandler->moduleExists('content_translation')) {
      $query->leftJoin('node', 'nt', 'n.tnid = nt.nid');
      $query->addField('nt', 'language', 'source_langcode');
    }

    if (isset($this->configuration['node_type'])) {
      $query->condition('n.type', $this->configuration['node_type']);
    }

    return $query;
  }


  /**
   * {@inheritdoc}
   */
  public function fields() {

    $fields = [
      'nid' => $this->t('Node ID'),
      'type' => $this->t('Type'),
      'title' => $this->t('Title'),
      'body' => $this->t('Body'),
      'format' => $this->t('Format'),
      'teaser' => $this->t('Teaser'),
      'node_uid' => $this->t('Node authored by (uid)'),
      'revision_uid' => $this->t('Revision authored by (uid)'),
      'created' => $this->t('Created timestamp'),
      'changed' => $this->t('Modified timestamp'),
      'status' => $this->t('Published'),
      'promote' => $this->t('Promoted to front page'),
      'sticky' => $this->t('Sticky at top of lists'),
      'revision' => $this->t('Create new revision'),
      'language' => $this->t('Language (fr, en, ...)'),
      'tnid' => $this->t('The translation set id for this node'),
      'timestamp' => $this->t('The timestamp the latest revision of this node was created.'),
    ];
    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    drush_print(' ');
    drush_print('- - - - - - - - - - - - - - - - - - - - - - - -');
    drush_print($row->getSourceProperty('title'));


    // format = 0 can happen when the body field is hidden. Set the format to 1
    // to avoid migration map issues (since the body field isn't used anyway).
    if ($row->getSourceProperty('format') === '0') {
      $row->setSourceProperty('format', $this->filterDefaultFormat);
    }

    if ($this->moduleExists('content') && $this->getModuleSchemaVersion('content') >= 6001) {
      foreach ($this->getFieldValues($row) as $field => $values) {
        $row->setSourceProperty($field, $values);
      }
    }
    $row_nid = $row->getSourceProperty('nid');


    // Make sure we always have a translation set.
    if ($row->getSourceProperty('tnid') == 0) {
      $row->setSourceProperty('tnid', $row_nid);
    }

    // get the entree values
    $query = $this->select('term_node', 'tn');
    // $query->fields('cte', ['field_entree_value']);
    $query->condition('tn.nid', $row_nid);
    $query->join('term_data', 'td', 'td.tid = tn.tid');
    $query->condition('td.vid', 2); // vid of voc entrees
    $query->addField('tn', 'tid');
    $query->distinct();
    $results = $query->execute()->fetchAll();
    $entrees = [];
    foreach ($results as $key => $value) {
      $entrees[] = array($value['tid']);
    }
    $row->setSourceProperty('entrees', $entrees);

    // Page type
    $query = $this->select('term_node', 'tn');
    $query->condition('tn.nid', $row_nid);
    $query->join('term_data', 'td', 'td.tid = tn.tid');
    $query->condition('td.vid', 1); // vid of voc page type
    $query->addField('tn', 'tid');
    $query->distinct();
    $results = $query->execute()->fetchAll();
    $pagetype = [];
    foreach ($results as $key => $value) {
      // avoid notice type (tid 8)
      // row will be skiped if empty
      if($value['tid'] !== "8"){
        drush_print('page type : '.$value['tid']);
        $pagetype[] = array($value['tid']);
      }else{
        drush_print('----- NOTICE -----');
      }
    }
    drush_print('pagetype empty : '.empty($pagetype));
    // if(count($pagetype) < 1){
    //   $pagetype = FALSE;
    // }
    $row->setSourceProperty('page_type', !empty($pagetype) ? $pagetype : 0);

    // son
    // TODO: pour les pieces sonores les fichiers ne sont pas enregistrés dans le champ car trop lourd. Ils sont sous forme de lien dans le corps du texte. Comment normaliser ça ??
    // $sons = [];
    // foreach ($row->getSourceProperty('field_mp3') as $key => $value) {
    //   $sons[] = array($value['fid']);
    // }
    // $row->setSourceProperty('sons_fid', $sons);
    $body = $row->getSourceProperty('body');
    preg_match_all('/href="(\/?sons\/[^"]+)"/', $body, $links);
    if(isset($links[1][0])){
      // drush_print('links : ', 0, null, false);
      // drush_print_r($links);
      $path = preg_replace('/^\//', '', $links[1][0]);
      // 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
        // TODO: is this working for both corpus and sons elements ??
        $new_nid = Database::getConnection('default', 'default')
          ->select('migrate_map_d6_edlp_sons', 'm')
          ->fields('m', ['destid1'])
          ->condition('sourceid1', $nid)
          ->execute()
          ->fetchField();
        // drush_print('new_nid : ', 0, null, false);
        // drush_print_r($new_nid);
        if($new_nid){
          $body = str_replace($path, "node/".$new_nid, $body);
        }
      }else{
        // drush_print('no source for path : ', 0, null, false);
        // drush_print_r($path);
      }
    }
    $row->setSourceProperty('body', $body);

    // visuel
    $visuels = [];
    foreach ($row->getSourceProperty('field_visuel') as $key => $value) {
      $visuels[] = array($value['fid']);
    }
    $row->setSourceProperty('visuels_fid', $visuels);

    // get the workflow status
    $query = $this->select('workflow_node', 'wn');
    $query->fields('wn', ['sid']);
    $query->condition('wn.nid', $row_nid);
    $results = $query->execute()->fetchField();
    // drush_print('workflow query results : ', 0, null, false);
    // drush_print_r($results);
    $row->setSourceProperty('workflow', $results);

    // fichiers attachés ??

    $row = parent::prepareRow($row);
    return $row;
  }


}
