<?php

namespace Drupal\materio_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\EntityManagerInterface;
use Drupal\Core\Extension\ModuleHandler;
use Drupal\Core\State\StateInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Locale\CountryManagerInterface;
use libphonenumber\PhoneNumber;
use libphonenumber\PhoneNumberUtil;
use libphonenumber\PhoneNumberFormat;
/**
 * Drupal 7 node source from database.
 *
 * @MigrateSource(
 *   id = "d7_user_profile",
 *   source_module = "profile2"
 * )
 */
class D7UserProfile extends FieldableEntity {

  /**
   * Phone Number util.
   *
   * @var \libphonenumber\PhoneNumberUtil
   */
  public $phoneUtils;

  /**
   * Country Manager service.
   *
   * @var \Drupal\Core\Locale\CountryManagerInterface
   */
  public $countryManager;

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration, StateInterface $state, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, CountryManagerInterface $country_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $migration, $state, $entity_manager);
    $this->moduleHandler = $module_handler;
    $this->phoneUtils = PhoneNumberUtil::getInstance();
    $this->countryManager = $country_manager;
  }

  /**
   * {@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.manager'),
      $container->get('module_handler'),
      $container->get('country_manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function query() {
    // Select node in its last revision.
    $query = $this->select('profile', 'p')
      ->fields('p', [
        'pid',
        'type',
        'uid',
        'label',
        'created',
        'changed',
      ])
      ->orderBy('changed');

    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $pid = $row->getSourceProperty('pid');
    $uid = $row->getSourceProperty('uid');
    $type = $row->getSourceProperty('type');
    // drush_print('-- '.$pid."\t".$uid."\t".$type);

    // Get Field API field values.
    foreach ($this->getFields('profile2', $type) as $field_name => $field) {
      // drush_print($field_name);
      $value = $this->getFieldValues('profile2', $field_name, $pid);
      $row->setSourceProperty($field_name, $value);
    }

    // merge : field_administrative_email & field_private_email into field_email
    // merge : field_private_name & field_name into field_name
    switch ($type) {
      case 'contact_operationnel':
        $row->setSourceProperty('field_email', $row->getSourceProperty('field_private_email'));
        $row->setSourceProperty('field_name', $row->getSourceProperty('field_private_name'));
        break;
      case 'adherent':
        $row->setSourceProperty('field_email', $row->getSourceProperty('field_administrative_email'));
        break;
    }

    // make sure that field_website url is absolute
    $field_website = $row->getSourceProperty('field_user_website');
    if(isset($field_website[0]['url'])){
      $url = $field_website[0]['url'];
      if(!strpos($url, 'http://')){
        $field_website[0]['url'] = 'http://'.$url;
        $row->setSourceProperty('field_user_website', $field_website);
      }
    }

    // convert phone field with libphonenumber
    $field_phone = $row->getSourceProperty('field_private_phone');
    if(isset($field_phone[0]['number']) && !empty($field_phone[0]['number'])){
      $national_number = $field_phone[0]['number'];
      $region = strtoupper($field_phone[0]['country_codes']);
      // isValidRegionCode($regionCode)
      if($this->phoneUtils->isPossibleNumber($national_number, $region)){
        $number = $this->phoneUtils->parse($national_number, $region);
        $row->setSourceProperty('field_private_phone', $this->phoneUtils->format($number, PhoneNumberFormat::E164));
      }else{
        // add bad phone number to memo field
        $memo .= "#migration : invalid phone number: ".$national_number.' region: '.$region."\n";
        drush_print('WARNING: phone number invalide; number: '.$national_number.' region: '.$region);
      }
    }

    // record migration errors in field_memo
    if(isset($memo)){
      $field_memo = $row->getSourceProperty('field_memo');
      $field_memo[0]['value'] .= "\n".$memo;
      $row->setSourceProperty('field_memo', $field_memo);
    }

    return parent::prepareRow($row);
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'pid' => $this->t('Profile ID'),
      'type' => $this->t('Type'),
      'uid' => $this->t('Title'),
      'label' => $this->t('Label'),
      'created' => $this->t('Created timestamp'),
      'changed' => $this->t('Modified timestamp'),
    ];
    return $fields;
  }

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

}
