<?php

namespace Drupal\localgov_elections\Plugin\views\field;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Field handler to flag the node type.
 *
 * @ViewsField("party_name")
 */
class PartyName extends FieldPluginBase {

  /**
   * Constructs a new plugin instance.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, protected EntityTypeManagerInterface $entityTypeManager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity_type.manager'),
    );
  }

  /**
   * Leave empty to avoid a query on this field.
   */
  public function query():void {

  }

  /**
   * Render function for the party_name field.
   *
   * Displays a participating party in an electoral area (Ward).
   *
   * @{inheritdoc}
   */
  public function render(ResultRow $values): mixed {
    $election = $values->_entity;

    // Iterate through each candidate and store votes.
    $party_name = NULL;
    $results = [];

    // Find all 'Areas vote' (localgov_area_vote) nodes referencing this
    // election.
    $query = $this->entityTypeManager->getStorage('node')->getQuery()
      ->condition('type', 'localgov_area_vote')
      ->condition('localgov_election', $election);
    $query->accessCheck(FALSE);
    $wards = $query->execute();

    // Add all candidate votes + spoils for each ward.
    foreach ($wards as $ward_id) {
      $ward = $this->entityTypeManager->getStorage('node')->load($ward_id);
      $candidates = $ward->get('localgov_election_candidates');

      foreach ($candidates->referencedEntities() as $candidate) {
        $party = $this->entityTypeManager->getStorage('taxonomy_term')->load($candidate->get('localgov_election_party')->target_id);
        $party_name = $party->getTitle->value;
        $results[] = ['name' => $party_name];
      }
    }

    // Return party names.
    if ($results) {
      $party_name = $results[0]['name'];
    }

    return $party_name;
  }

}
