<?php
namespace ModulesAbstract\PluginReports\ConfigUDEFListing;

abstract class Model extends \App\Mvc\Model_ListingAbstract
{

	/**
	 * Returns the array of UDEF configs
	 * @return Array
	 */
	abstract public function getUDEFConfigs();

	/**
	 * Saves the array of UDEF configs
	 * @param Array $UDEFConfigs
	 */
	abstract public function saveUDEFConfigs(array $UDEFConfigs);

	/**
	 * Returns the array of UDEF fields
	 * @return array
	 */
	abstract public function getUDEFPossibleFields();

	/**
	 * Get the results list with all the filtering applied
	 *
	 * @param array $UDEFResults
	 * @param \App\Mvc\View\Listing\Members\Params $listingParams
	 * @return array
	 */
	protected function sliceResultsList(array $UDEFResults, \App\Mvc\View\Listing\Members\Params $listingParams)
	{
		$currentPage = $listingParams->getCurrentPage();
		$resultsPerPage = $listingParams->getResultsPerPage();

		if (!$resultsPerPage) {
			throw new \Exception(sprintf("[%s] resultsPerPage not set", __METHOD__));
		}

		$UDEFResults = array_slice($UDEFResults, $currentPage*$resultsPerPage, $resultsPerPage, true);

		return $UDEFResults;
	}

	/**
	 * Check if a UDEF should be displayed
	 * @param array $UDEF
	 * @param array $filters
	 * @return bool
	 */
	protected function UDEFShouldBeDisplayed(array $UDEF, array $filters)
	{
		// filter by corporateFilter
		if ($filters['corporateFilter']) {
			if ($UDEF['corporateFilter'] != $filters['corporateFilter']) {
				return false;
			}
		}

		return true;
	}


	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Model_ListingAbstract::list_execute()
	 */
	function list_execute(\App\Mvc\View\Listing\Members\Params $listingParams)
	{
        $UDEFConfigs = $this->getUDEFConfigs();

		// pre-extract columns
		$filters = $listingParams->getFilters();
		$listedUDEFs = [];
		foreach ($UDEFConfigs as $k=>$UDEFConfig) {
			if ($this->UDEFShouldBeDisplayed($UDEFConfig, ($filters?$filters:[]))) {
				$UDEFConfig['id'] = $k;
				$listedUDEFs[$k] = $UDEFConfig;
			}
		}

		$totalRecordsCount = count($listedUDEFs);
		$listedUDEFs = $this->sliceResultsList($listedUDEFs, $listingParams);

        $this->recordsList = $listedUDEFs;
		$this->totalRecordsCount = $totalRecordsCount;
	}

}
