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

use CRM_Dataprocessor_ExtensionUtil as E;

class CRM_DataprocessorSearch_Form_Task_SearchActionDesigner extends CRM_Searchactiondesigner_Form_Task_Task {

  /** @var CRM_DataprocessorSearch_Form_AbstractSearch */
  protected $searchForm;

  protected function setEntityShortName() {
    self::$entityShortname = 'DataprocessorSearch';
  }

  public function preProcess() {
    $this->setEntityShortName();
    $session = CRM_Core_Session::singleton();
    $url = $session->readUserContext();
    $session->replaceUserContext($url);

    $selectionCount = 0;
    $dataProcessorSearchForm = $this->controller->getPage($this->controller->getSearchName());
    if ($dataProcessorSearchForm instanceof CRM_DataprocessorSearch_Form_AbstractSearch) {
      $this->searchForm = $dataProcessorSearchForm;
      $selectionCount = $this->searchForm->getSelectionCount();
    }

    $searchFormValues = $this->controller->exportValues($this->get('searchFormName'));
    $this->_task = $searchFormValues['task'];
    $className = 'CRM_' . ucfirst(self::$entityShortname) . '_Task';
    $entityTasks = $className::tasks();
    $this->assign('taskName', $entityTasks[$this->_task]);

    if (strpos($this->_task,'searchactiondesigner_') !== 0) {
      throw new \Exception(E::ts('Invalid search task'));
    }
    $this->searchTaskId = substr($this->_task, 21);

    $this->searchTask = civicrm_api3('SearchTask', 'getsingle', array('id' => $this->searchTaskId));
    $this->assign('searchTask', $this->searchTask);
    $this->assign('status', E::ts("Number of selected records: %1", array(1=>$selectionCount)));
  }

  public function postProcess() {
    $this->_entityIds = $this->searchForm->getSelectedIds();
    parent::postProcess();
  }


}
