<?php

namespace Drupal\materio_migrate\Plugin\migrate\source;

use Drupal\user\Entity\User;
use Drupal\migrate\Plugin\migrate\source\SqlBase;
use Drupal\migrate\Row;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Plugin\migrate\process\MigrationLookup;

/**
 * Minimalistic example for a SqlBase source plugin.
 *
 * @MigrateSource(
 *   id = "d7_flaglistitems_materio",
 *   source_module = "flag_lists"
 * )
 */
class D7FlagListItemsMaterio extends SqlBase {

  /**
   * {@inheritdoc}
   */
  public function query() {
    // Source data is queried from 'curling_games' table.
    $query = $this->select('flag_lists_content', 'c');
    $query->join('flag_lists_flags', 'f', 'c.fid = f.fid');
    // only import flaglist items for active users
    $query->join('users_roles', 'ur', 'c.uid = ur.uid');
    $query->condition('ur.rid', [3,4,6,10,11,13], 'IN');
    $query->fields('c', [
      'fcid',
      'fid',
      'entity_type',
      'entity_id',
      'uid',
      'sid',
      'timestamp',
    ])
      ->fields('f', [
        'name',
        'title',
      ]);
    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'fcid' => $this->t('Flag content id'),
      'fid' => $this->t('Flag lists id #'),
      'entity_type' => $this->t('Entity type'),
      'entity_id' => $this->t('Entity #'),
      'uid' => $this->t('Owner'),
      'sid' => $this->t('Sid'),
      'timestamp' => $this->t('Timestamp'),
    ];
    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    return [
      'fcid' => [
        'type' => 'integer',
        'alias' => 'f',
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {

    $messenger = \Drupal::messenger();
    $logger = \Drupal::logger('flag_lists');

    // // Check and get the user name.
    // $uid = $row->getSourceProperty('uid');
    // $user = User::load($uid);
    // if (!empty($user)) {
    //   $owner = $uid;
    // }
    // else {
    //   $owner = 1;
    // }
    // $row->setSourceProperty('uid', $owner);

    // Check if the flagging collection exist.
    // $found = FALSE;
    $fid = $row->getSourceProperty('fid');
    $database = \Drupal::database();
    $fidquery = $database->select('migrate_map_d7_flaglists', 'm')
      ->condition('m.sourceid1', $fid)
      ->fields('m', ['sourceid1', 'destid1']);
    $result = $fidquery->execute();
    foreach ($result as $record) {
      if($record){
        $dfid = $record->destid1;
        break;
      }
    }
    // if flag_collection already imported
    if($dfid){
      $flagListsService = \Drupal::service('flaglists');
      $flagcoll = $flagListsService->getFlaggingCollectionById($dfid);
      $relatedFlag = $flagcoll->getRelatedFlag();
      $row->setSourceProperty('baseflag', $relatedFlag->id());

      $row->setSourceProperty('flagcolname', $flagcoll->getName());
    }

    // TODO: dest_entity_id (for name composition)
    $entity_id = $row->getSourceProperty('entity_id');
    // check destid from materiau
    $query_entityid = $database->select('migrate_map_d7_node_materiau', 'm')
      ->condition('m.sourceid1', $entity_id)
      ->fields('m', ['sourceid1', 'destid1']);
    $result = $query_entityid->execute();
    foreach ($result as $record) {
      if($record){
        $dest_entity_id = $record->destid1;
        break;
      }
    }
    // check destid from articles (ex breves)
    if(!$dest_entity_id){
      $query_entityid = $database->select('migrate_map_d7_node_article', 'm')
        ->condition('m.sourceid1', $entity_id)
        ->fields('m', ['sourceid1', 'destid1']);
      $result = $query_entityid->execute();
      foreach ($result as $record) {
        if($record){
          $dest_entity_id = $record->destid1;
          break;
        }
      }
    }
    if($dest_entity_id){
      $row->setSourceProperty('dest_entity_id', $dest_entity_id);
    }else{
      $row->setSourceProperty('dest_entity_id', $entity_id);
    }

    return parent::prepareRow($row);
  }

}
