<?php
// https://understanddrupal.com/articles/how-debug-drupal-migrations-part-2

namespace Drupal\popsu_migrate\Plugin\migrate\source;

use Drupal\migrate\Row;
use Drush\Drush;
use Drupal\paragraphs\Entity\Paragraph;

// use Drupal\popsu_migrate\Plugin\migrate\source\D7Programme;

/**
 * Drupal 7 node source from database.
 *
 * @MigrateSource(
 *   id = "d7_node_programme",
 *   source_module = "node"
 * )
 */
class D7NodeProgramme extends D7Programme {

  /**
   * {@inheritdoc}
   */
  public function query() {
    $query = parent::query($row);

    // field_popsu_special_typetaxo 31 (Acueile)
    $query->leftJoin('field_revision_field_popsu_special_typetaxo', 'ff', 'ff.revision_id = n.vid');
    $query->fields('ff', [
      'field_popsu_special_typetaxo_tid'
    ]);
    $query->condition('ff.field_popsu_special_typetaxo_tid', 31);

    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $nid = $row->getSourceProperty('nid');
    $vid = $row->getSourceProperty('vid');
    $type = $row->getSourceProperty('type');
    $title = $row->getSourceProperty('title');
    Drush::output()->writeln('- - - - ' . $title . '- - - - ');

    // Get Field API field values.
    foreach ($this->getFields('node', $type) as $field_name => $field) {
      $row->setSourceProperty($field_name, $this->getFieldValues('node', $field_name, $nid, $vid, NULL));
    }

    // title from taxo term
    $field_popsu_special_popsu_tid = $row->getSourceProperty('field_popsu_special_popsu')[0]['tid'];
    $q = $this->select('taxonomy_term_data', 'ttd')
      ->fields('ttd', ['tid','name'])
      ->condition('tid', $field_popsu_special_popsu_tid);
    $term = $q->execute()->fetchAll();
    // Drush::output()->writeln(dump($term));
    $row->setSourceProperty('term_title', $term[0]['name']);

    // text intro
    $body = $row->getSourceProperty('field_popsu_special_body');
    $row->setSourceProperty('body', $body[0]['value']);
    $row->setSourceProperty('body_summary', $body[0]['summary']);

    // associateds
    $associateds = $this->getAssociatedSpecial($field_popsu_special_popsu_tid);
    // Drush::output()->writeln(dump($associateds));

    // texts (paragraphe)
    $text = $row->getSourceProperty('field_popsu_special_text');
    $text[0]['format'] = 'wysiwyg';
    $p = Paragraph::create(['type' => 'textes']);
    $p->set('field_texte', $text)
      ->set('field_titre', $row->getSourceProperty('title'))
      ->isNew();
    $p->save();

    $text_paragraphe = array(
      array(
        'target_id' => $p->id(),
        'target_revision_id' => $p->getRevisionId(),
      ),
    );
    $row->setSourceProperty('text_paragraphe', $text_paragraphe);

    // Sous partie
    // looping through special_type
    $sous_parties = array();
    foreach (['colloques', 'publications'] as $special_type) {
      $ps = array();
      // looping through nodes
      foreach ($associateds[$special_type] as $key => $special) {
        // looping through fields
        foreach (['field_popsu_special_body', 'field_popsu_special_text'] as $field) {
          if (!empty($special[$field])) {
            // creating the sous partie contents (sub paragraphes)
            $text = $special[$field][0];
            // TODO: bad format http://dev.d9.popsu.archi.fr/node/213/edit?
            $text['format'] = 'wysiwyg';
            $p = Paragraph::create(['type' => 'sous_partie_programme_contents']);
            $p->set('field_texte', $text)
              ->set('field_titre', $special['title'])
              // TODO ->set('field_liste_contenus',) migration_lookup on popsu_colloques -> evenements
              ->isNew();
            $p->save();
            $ps[] = array(
              'target_id' => $p->id(),
              'target_revision_id' => $p->getRevisionId(),
            );
          }
        }
      }
      if (!empty($ps)) {
        // creating sous partie (paragraphe)
        $p = Paragraph::create(['type' => 'sous_partie_programme']);
        $p->set('field_sous_partie_contenus', $ps)
          ->set('field_titre', $special_type)
          ->isNew();
        $p->save();
        $sous_parties[] = array(
          'target_id' => $p->id(),
          'target_revision_id' => $p->getRevisionId(),
        );
      }
    }
    if (!empty($sous_parties)) {
      $row->setSourceProperty('sous_parties', $sous_parties);
    }

    // Partenaires
    $ps = array();
    // looping through nodes
    foreach ($associateds['partenaires'] as $key => $special) {
      $p = Paragraph::create(['type' => 'partenaires']);
      $p->set('field_nom_partenaire', $special['title']);
      // texts
      if(!empty($special['field_popsu_special_body']) || !empty($special['field_popsu_special_text'])){
        $text = array(
          array(
            'value' => '',
            'summary' => '',
            'format' => 'wysiwyg'
          ),
        );
        foreach (['field_popsu_special_body', 'field_popsu_special_text'] as $src_field) {
          if (!empty($special[$src_field])) {
            $text[0]['value'] .= $special[$src_field][0]['value'];
            $text[0]['summary'] .= isset($special[$src_field][0]['summary']) ? $special[$src_field][0]['summary'] : '';
          }
        }
        $p->set('field_presentation', $text);
      }
      // files
      // 'field_fichiers' => ['field_popsu_special_insert_intro', 'field_popsu_special_insert'],
      $files = array();
      foreach (['field_popsu_special_insert_intro', 'field_popsu_special_insert'] as $field) {
        if (!empty($special[$field])) {
          // Drush::output()->writeln(dump($special[$field]));
          foreach ($special[$field] as $file) {
            // Drush::output()->writeln(dump($file));
            // change file fid from migration lookup
            $database = \Drupal::database();
            $fidquery = $database->select('migrate_map_d7_allpublicfiles', 'm')
              ->condition('m.sourceid1', $file['fid'])
              ->fields('m', ['sourceid1', 'destid1']);
            $result = $fidquery->execute();
            foreach ($result as $record) {
              if($record){
                $dfid = $record->destid1;
                break;
              }
            }
            if ($dfid) {
              $file['target_id'] = $dfid;
              unset($file['fid']);
              $files[] = $file;
            }
          }
        }
      }
      if (!empty($files)) {
        Drush::output()->writeln(dump($files));
        $p->set('field_fichiers', $files);
      }

      $p->isNew();
      $p->save();
      $ps[] = array(
        'target_id' => $p->id(),
        'target_revision_id' => $p->getRevisionId(),
      );
    }
    if (!empty($ps)) {
      $row->setSourceProperty('partenaires', $ps);
    }

    // fichiers
    // files from current node
    $fichiers = array();
    foreach ($row->getSourceProperty('field_popsu_special_insert') as $value) {
      $fichiers[] = $value;
    }
    foreach ($row->getSourceProperty('field_popsu_special_insert_intro') as $value) {
      $fichiers[] = $value;
    }
    // files from associated nodes (colloques, publications, partenaires)
    foreach ( ['colloques', 'publications'] as $name) {
      foreach ($associateds[$name] as $key => $asso) {
        // tried with array merge but it failed
        // and apparently foreach is faster than array_merge
        foreach ($asso['field_popsu_special_insert'] as $value) {
          $fichiers[] = $value;
        }
        foreach ($asso['field_popsu_special_insert_intro'] as $value) {
          $fichiers[] = $value;
        }
      }
    }
    $row->setSourceProperty('fichiers', $fichiers);

    return parent::prepareRow($row);
  }

}
