<?php
/**
 * Copyright (C) 2023  Jaap Jansma (jaap.jansma@civicoop.org)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

use Civi\DataProcessor\Output\DirectDownloadExportOutputInterface;

class CRM_DataprocessorOutputExport_Form_OutputExport extends CRM_Core_Form {

  /**
   * @var \Civi\DataProcessor\ProcessorType\AbstractProcessorType
   */
  protected $dataProcessorClass;

  /**
   * @var array
   */
  protected $dataProcessor;

  /**
   * @var array
   */
  protected $searchValues;

  /**
   * @var string
   */
  protected $idFieldName;

  /** @var array */
  protected $selectedIds;

  /** @var string|null */
  protected $sortFieldName;

  /** @var string */
  protected $sortDirection = 'ASC';

  /**
   * @var \Civi\DataProcessor\Output\ExportOutputInterface
   */
  protected $outputClass;

  /** @var array */
  protected $output;

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


  protected function setDataProcessorSearchForm(CRM_DataprocessorSearch_Form_AbstractSearch $form) {
    $this->searchForm = $form;
    $this->searchValues = $this->controller->exportValues($this->controller->getSearchName());
    $this->dataProcessorClass = $form->getDataProcessorClass();
    $this->dataProcessor = $form->getDataProcessor();
    $this->idFieldName = $form->getIdFieldName();
    if ($form->getSort() && $form->getSort()->getCurrentSortID() > 1) {
      $sortField = $form->getSort()->_vars[$form->getSort()->getCurrentSortID()];
      if ($form->getSort()->getCurrentSortDirection() == CRM_Utils_Sort::DESCENDING) {
        $this->sortDirection = 'DESC';
      }
      $this->sortFieldName = $sortField['name'];
    }
  }

  /**
   * @param bool $redirectBack
   *   Redirect back after a direct download.
   *
   * @return void
   */
  protected function runExport(bool $redirectBack=false) {
    $selectedIds = [];
    if (!$this->searchForm->allRecordsSelected()) {
      $selectedIds = $this->searchForm->getSelectedIds();
    }
    $this->outputClass->downloadExport($this->dataProcessorClass, $this->dataProcessor, $this->output, $this->searchValues, $this->sortFieldName, $this->sortDirection, $this->idFieldName, $selectedIds, $redirectBack);
  }

  public function preProcess() {
    $export_id = $this->controller->get('export_id');
    $factory = dataprocessor_get_factory();

    $dataProcessorSearchForm = $this->controller->getPage($this->controller->getSearchName());
    if ($dataProcessorSearchForm instanceof CRM_DataprocessorSearch_Form_AbstractSearch) {
      $this->setDataProcessorSearchForm($dataProcessorSearchForm);
      try {
        $this->output = civicrm_api3("DataProcessorOutput", "getsingle", ['id' => $export_id]);
        $this->outputClass = $factory->getOutputByName($this->output['type']);
        if ($this->outputClass instanceof DirectDownloadExportOutputInterface) {
          $this->runExport();
        }
      } catch (CiviCRM_API3_Exception $e) {
      }
    }
  }

}
