<?php

namespace Drupal\ufc\Commands;

use Drupal\node\Entity\Node;
use Drush\Commands\DrushCommands;

class UfcCommands extends DrushCommands {

  /**
   * Update fights with their event date.
   *
   * @command ufc:update-fight-dates
   * @aliases ufc-ufd
   */
  public function updateFightDates() {
    // Get all fights
    // For each fight
    //  Go get event date.
    //  Add to new field
    //  Save.
    $fights = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => 'fight']);
    foreach ($fights as $fight) {
      $fight->field_fight_date = $this->getEventDateTimestampFromFight($fight);
      if ($fight->save()) {
        $this->output->writeln($fight->title->value . " updated successfully.");
      }
      else {
        $this->output->writeln($fight->title->value . " failed.");
      }
    }
  }


  private function getEventDateTimestampFromFight(Node $fight_node) {
    // Get field value.
    $event_date_value = $fight_node->field_event->entity->field_event_date->value;
    assert($event_date_value, !null);

    return strtotime($event_date_value);
  }

}
