<?php
/**
 * @author Jaap Jansma <jaap.jansma@civicoop.org>
 * @license AGPL-3.0
 */

namespace Civi\DataProcessor\FieldOutputHandler;

use Civi\API\Exception\UnauthorizedException;
use CRM_Core_Exception;
use Civi\Api4\Event;
use Civi\Api4\Participant;
use CRM_Dataprocessor_ExtensionUtil as E;

class EventAvailabilityInfoFieldOutputHandler extends AbstractSimpleFieldOutputHandler {

  protected $show;

  /**
   * Returns the data type of this field
   *
   * @return String
   */
  protected function getType() {
    if ($this->show == 'available_places') {
      return 'Integer';
    }
    return 'String';
  }

  /**
   * Initialize the processor
   *
   * @param String $alias
   * @param String $title
   * @param array $configuration
   * @param \Civi\DataProcessor\ProcessorType\AbstractProcessorType $processorType
   */
  public function initialize($alias, $title, $configuration) {
    parent::initialize($alias, $title, $configuration);
    if (isset($configuration['show'])) {
      $this->show = $configuration['show'];
    }
  }

  /**
   * Returns the formatted value
   *
   * @param $rawRecord
   * @param $formattedRecord
   *
   * @return \Civi\DataProcessor\FieldOutputHandler\FieldOutput
   */
  public function formatField($rawRecord, $formattedRecord) {
    $event_id = $rawRecord[$this->inputFieldSpec->alias];
    $outputValue = '';

    try {
      $event = Event::get(FALSE)
        ->addWhere('id', '=', $event_id)
        ->execute()
        ->first();
      if (isset($event['max_participants'])) {
        $participantCount = Participant::get(FALSE)
          ->addWhere('event_id', '=', $event_id)
          ->addWhere('status_id.is_counted', '=', TRUE)
          ->execute()
          ->count();
        $fullText = '';
        $availablePlaces = $event['max_participants'] - $participantCount;
        if (!$availablePlaces) {
          if (!empty($event['has_waitlist']) && !empty($event['waitlist_text'])) {
            $fullText =  $event['waitlist_text'];
          } else {
            $fullText = $event['event_full_text'];
          }
        }
        switch ($this->show) {
          case 'full_text':
            $outputValue = $fullText;
            break;
          case 'available_places':
            $outputValue = $availablePlaces;
            break;
        }
      }
    }
    catch (UnauthorizedException|CRM_Core_Exception $e) {
    }

    $output = new FieldOutput($outputValue);
    return $output;
  }

  /**
   * When this handler has additional configuration you can add
   * the fields on the form with this function.
   *
   * @param \CRM_Core_Form $form
   * @param array $field
   */
  public function buildConfigurationForm(\CRM_Core_Form $form, $field=array()) {
    parent::buildConfigurationForm($form, $field);
    $form->add('select', 'show', E::ts('Show'), ['full_text' => E::ts('Full text or wait list message when event is full'), 'available_places' => E::ts('The number of available places')], true, array(
      'style' => 'min-width:250px',
      'class' => 'crm-select2 huge',
      'placeholder' => E::ts('- select -'),
      'multiple' => false,
    ));

    if (isset($field['configuration'])) {
      $configuration = $field['configuration'];
      $defaults = array();
      if (isset($configuration['show'])) {
        $defaults['show'] = $configuration['show'];
      }
      $form->setDefaults($defaults);
    } else {
      $defaults['show'] = 'full_text';
      $form->setDefaults($defaults);
    }
  }

  /**
   * When this handler has configuration specify the template file name
   * for the configuration form.
   *
   * @return false|string
   */
  public function getConfigurationTemplateFileName() {
    return "CRM/Dataprocessor/Form/Field/Configuration/EventAvailabilityInfoFieldOutputHandler.tpl";
  }


  /**
   * Process the submitted values and create a configuration array
   *
   * @param $submittedValues
   * @return array
   */
  public function processConfiguration($submittedValues) {
    $configuration = parent::processConfiguration($submittedValues);
    $configuration['show'] = $submittedValues['show'];
    return $configuration;
  }


}
