<?php
namespace Drupal\popsu_migrate\Plugin\migrate\source;

use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\migrate\Row;
use Drupal\migrate_drupal\Plugin\migrate\source\d7\FieldableEntity;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandler;
use Drupal\Core\State\StateInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
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_projet",
 *   source_module = "node"
 * )
 */
class D7NodeProjet extends FieldableEntity {
  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The logger channel.
   *
   * @var \Drupal\Core\Logger\LoggerChannelInterface
   */
  protected $logger;


  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration, StateInterface $state, EntityTypeManagerInterface $entity_manager, ModuleHandlerInterface $module_handler,LoggerChannelFactoryInterface $loggerFactory) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $migration, $state, $entity_manager);
    $this->moduleHandler = $module_handler;
    $this->logger = $loggerFactory->get('popsu_migration');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $migration,
      $container->get('state'),
      $container->get('entity_type.manager'),
      $container->get('module_handler'),
      $container->get('logger.factory')
    );
  }

  /**
   * The join options between the node and the node_revisions table.
   */
  const JOIN = 'n.vid = nr.vid';

  /**
   * {@inheritdoc}
   */
  public function query() {
    // Select node in its last revision.
    $query = $this->select('node_revision', 'nr')
      ->fields('n', [
        'nid',
        'type',
        'uid',
        'language',
        'status',
        'created',
        'changed',
      ])
      ->fields('nr', [
        'vid',
        'title',
        'log',
        'timestamp',
      ])
      ->orderBy('changed');

    $query->addField('n', 'uid', 'node_uid');
    $query->addField('nr', 'uid', 'revision_uid');
    $query->innerJoin('node', 'n', static::JOIN);

    $query->condition('n.type', ['popsu_ville', 'popsu_ville_europe', 'popsu_projet'], 'IN');

    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 . ' ('.$nid.')' . '- - - - ');

    $memo = '';
    $memo .= "#migration : old nid = ".$nid."\n";
    $memo .= "#migration : old content type = ".$type."\n";

    // Get Field API field values.
    foreach ($this->getFields('node', $type) as $field_name => $field) {
      $field_values = $this->getFieldValues('node', $field_name, $nid, $vid, NULL);
      $row->setSourceProperty($field_name, $field_values);
      switch ($field_name) {
        // ville
        case 'field_popsu_ville_ville':
          $ville = $field_values;
          break;
        case 'field_popsu_villeur_ville':
          $ville = $field_values;
          break;
        case 'field_popsu_projet_ville':
          $ville = $field_values;
          break;
        // programme
        case 'field_popsu_ville_popsu':
          $field_programme = $field_values;
          break;
        case 'field_popsu_villeur_popsu':
          $field_programme = $field_values;
          break;
        case 'field_popsu_projet_popsu':
          $field_programme = $field_values;
          break;
        case 'field_popsu_ville_body':
          $field_body = $field_values;
          break;
        case 'field_popsu_villeur_body':
          $field_body = $field_values;
          break;
        case 'field_popsu_projet_presentation':
          $field_body = $field_values;
          break;
      }
    }
    if ($field_programme) {
      // Drush::output()->writeln(dump($field_programme));
      $tid = $field_programme[0]['tid'];
      // get the node (popsu_special) from the tid for migration_lookup
      $query = $this->select('node_revision', 'nr')
        ->fields('n', ['nid','type'])
        ->fields('nr', ['vid'])
        ->orderBy('changed');
      $query->innerJoin('node', 'n', static::JOIN);
      $query->condition('n.type', 'popsu_special');
      // field_popsu_special_typetaxo
      // filter to get the right special type (colloques, publication, etc)
      $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);
      // field_popsu_special_popsu
      // filter to get right popsu (popsu 1, popsu europe, etc)
      $query->leftJoin('field_revision_field_popsu_special_popsu', 'sp', 'sp.revision_id = n.vid');
      $query->fields('sp', ['field_popsu_special_popsu_tid']);
      $query->condition('sp.field_popsu_special_popsu_tid', $tid);

      $prog = $query->execute()->fetchAll();

      $row->setSourceProperty('field_programme', array(array('nid'=>$prog[0]['nid'])));
    } else {
      Drush::output()->writeln('NO PROGRAMME');
      $memo .= "#migration : NO PROGRAMME\n";
    }

    if ($field_popsu_projet_comparatif = $row->getSourceProperty('field_popsu_projet_comparatif')) {
      // Drush::output()->writeln(dump($field_comparatifs_associes));
      $row->setSourceProperty('field_comparatifs_associes', $field_popsu_projet_comparatif);
    }

    $field_themes_lies = array();
    $field_projets_lies = array();
    if ($field_popsu_projet_lies = $row->getSourceProperty('field_popsu_projet_lies')) {
      // Drush::output()->writeln(dump($field_popsu_projet_lies));
      foreach ($field_popsu_projet_lies as $key => $value) {
        // check if theme
        $q = $this->select('node', 'n')
          ->fields('n', ['nid','type'])
          ->condition('n.nid', $value['nid'])
          ->condition('n.type', ['popsu_theme_local', 'popsu_projet'], 'IN');
        $res = $q->execute()->fetchAll();
        if (!empty($res)) {
          // Drush::output()->writeln(dump($res));
          switch ($res[0]['type']) {
            case 'popsu_theme_local':
              $field_themes_lies[] = $value;
              break;
            case 'popsu_projet':
              $field_projets_lies[] = $value;
              break;
          }
        }
      }
    }

    if (!empty($field_projets_lies)) {
      // Drush::output()->writeln(dump($field_themes_lies));
      $row->setSourceProperty('field_projets_lies', $field_projets_lies);
    }

    // get the popsu_projet_europe nodes for popsu_ville_europe
    // we need themes and imags
    if ($type === 'popsu_ville_europe') {
      $query = $this->select('node_revision', 'nr')
        ->fields('n', ['nid','type'])
        ->fields('nr', ['vid'])
        ->orderBy('changed');
      $query->innerJoin('node', 'n', static::JOIN);
      $query->condition('n.type', 'popsu_projet_europe');
      // field_popsu_projeteur_ville
      // filter to get the right node
      $query->leftJoin('field_data_field_popsu_projeteur_ville', 'v', 'v.revision_id = n.vid');
      $query->fields('v', ['field_popsu_projeteur_ville_tid']);
      $query->condition('v.field_popsu_projeteur_ville_tid', $ville[0]['tid']);
      $popsu_projet_europe = $query->execute()->fetchAll();

      foreach ($popsu_projet_europe as $key => $value) {
        // Get Field API field values.
        foreach ($this->getFields('node', 'popsu_projet_europe') as $field_name => $field) {
          $popsu_projet_europe[$key][$field_name] = $this->getFieldValues('node', $field_name, $value['nid'], $value['vid'], NULL);
        }
        // get the themes
        if (!empty($popsu_projet_europe[$key]['field_popsu_projeteur_theme'])) {
          foreach ($popsu_projet_europe[$key]['field_popsu_projeteur_theme'] as $theme) {
            $field_themes_lies[] = $theme;
          }
        }
        // TODO: get the images
      }
      // Drush::output()->writeln(dump($popsu_projet_europe));
    }
    if (!empty($field_themes_lies)) {
      // Drush::output()->writeln(dump($field_themes_lies));
      $row->setSourceProperty('field_themes_lies', $field_themes_lies);
    }

    // Body
    if ($field_body) {
      $field_body[0]['format'] = 'wysiwyg';
      $row->setSourceProperty('body', $field_body);
    }

    // Diaporama
    $field_diaporama = array();
    $img_src_fields = array(
      'field_popsu_ville_images_illustr',
      'field_popsu_projeteur_thumb',
      'field_popsu_projeteur_diapo',
      'field_popsu_projet_imageintro',
      'field_popsu_projet_imagelocalise',
    );
    foreach ($img_src_fields as $field_name) {
      if ($imgs = $row->getSourceProperty($field_name)) {
        foreach ($imgs as $img) {
          $field_diaporama[] = $img;
        }
      }
    }
    if (!empty($field_diaporama)) {
      $row->setSourceProperty('diaporama', $field_diaporama);
    }

    # Text paragraphe
    $text_fields = array(
      'field_popsu_projet_methodo' => 'Démarche & méthodologie',
      'field_popsu_projet_demarche' => 'Chronologie',
      'field_popsu_projet_programme' => 'Programme',
    );
    $textes_paragraphes = array();
    foreach ($text_fields as $key => $title) {
      if ($text = $row->getSourceProperty($key)){
        $text[0]['format'] = 'wysiwyg';
        $p = Paragraph::create(['type' => 'textes']);
        $p->set('field_texte', $text)
        ->set('field_titre', $title)
        ->isNew();
        $p->save();

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

    # equipe paragraphe
    $equipe_fields = array(
      'field_popsu_ville_equipe' => 'Equipe de recherche',
      'field_popsu_ville_coordinateur' => 'Coordinateur des acteurs',
      'field__elus' => 'Elus',
      'field_professionnels' => 'Professionnels',
      'field_responsables_scientifiques' => 'Responsables scientifiques',
      'field_chercheurs' => 'Chercheurs',
      'field_popsu_projet_acteurs' => 'Acteurs',
    );
    $equipes_paragraphes = array();
    foreach ($equipe_fields as $field_name => $type) {
      if ($text = $row->getSourceProperty($field_name)){
        $text[0]['format'] = 'wysiwyg';
        $p = Paragraph::create(['type' => 'equipes']);
        $p->set('field_texte_intro', $text)
        ->set('field_type_equipe', $type)
        ->isNew();
        $p->save();

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

    // field_popsu_ville_partenairestxt NO DATA IN BDD
    $partenaires_paragraphes = array();
    if ($logo_partenaires = $row->getSourceProperty('field_popsu_ville_partenairesimg')){
      foreach ($logo_partenaires as $value) {
        $fid = $value['fid'] ;
        // manual migration_lookup for new fid
        $database = \Drupal::database();
        $fidquery = $database->select('migrate_map_d7_allpublicfiles', 'm')
          ->condition('m.sourceid1', $fid)
          ->fields('m', ['sourceid1', 'destid1']);
        $result = $fidquery->execute();
        foreach ($result as $record) {
          if($record){
            $target_id = $record->destid1;
            break;
          }
        }
        if ($target_id) {
          $value['target_id'] = $target_id;
          unset($value['fid']);
          $p = Paragraph::create(['type' => 'partenaires']);
          $p->set('field_logo_partenaire', $value)
          ->isNew();
          $p->save();

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

    // record migration errors in field_memo
    if(isset($memo)){
      $field_memo = array(
        array(
          'value' => $memo
        )
      );
      $row->setSourceProperty('field_memo', $field_memo);
    }

    return parent::prepareRow($row);
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'nid' => $this->t('Node ID'),
      'type' => $this->t('Type'),
      'title' => $this->t('Title'),
      '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 getIds() {
    $ids['nid']['type'] = 'integer';
    $ids['nid']['alias'] = 'n';
    return $ids;
  }

}
