<?php

// TODO: after populate data, we should index the table as well...

namespace App\QuickReports\PivotTables\Source;

abstract class GeneralAbstract
{
	/**
	 * The pivot table db table name.
	 * @var String $dbTable
	 */
	protected $dbTable = null;

	/**
	 * Stores and checks the db table.
	 * @throws \Exception
	 */
	public function __construct()
	{

		// store and check the db table name
		$this->dbTable = $this->getDbTable();
		if (!$this->dbTable) {
			throw new \Exception('No table name set for `'.__CLASS__.'`.');
		}

	}


	/**
	 * Returns the db table name that manages the pivot source.
	 * @return String
	 */
	abstract protected function getDbTable();

	/**
	 * Initializes the filters for the current filters of the pivot source.
	 */
	abstract protected function initializeFilters();


	/**
	 * Reloads all records in the pivot table source (truncates old table content and repopulates it).
	 */
	public function reloadData()
	{

		// update status of the current pivot source
		$pivotSource = stripClassNamespace(get_called_class());

		$db = \DB::getInstance();

		// pivot configure object
		$pivotCfg = \App\QuickReports\PivotTables\Configs::getInstance($pivotSource);

		// FLUSH THE OLD CACHE ////////////////////////////////////////////////////////////////////
		$cacheObj = new \Engine\Cache\DiskWithLRU();

		$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();
		$cacheObj->setPath($CFG['paths']['quickReportsCache']);
		$cacheObj->flush();

		// CHECK PIVOT SOURCE FILTERS /////////////////////////////////////////////////////////////
		$this->checkFilters();

		// update stats to 'populatingContent'
		\DB::startTransaction();
		$pivotCfg->status = 'populatingContent';
		$pivotCfg->startPopulateTimestamp = time();
		$pivotCfg->keepAliveTimestamp = null;
		$pivotCfg->finishPopulateTimestamp = null;
		\DB::commitTransaction();

		// TRUNCATE THE TABLE /////////////////////////////////////////////////////////////////////
		$db->Execute("TRUNCATE TABLE `{$this->dbTable}`");

		// POPULATE THE NEW DATA //////////////////////////////////////////////////////////////////
		$this->populateData();

		// update stats to 'ok'
		\DB::startTransaction();
		$pivotCfg->status = 'ok';
		$pivotCfg->finishPopulateTimestamp = time();
		\DB::commitTransaction();

	}


	/**
	 * Checks the filters collected for this pivot source.
	 */
	abstract protected function checkFilters();

	/**
	 * Populates the actual data for the pivot table.
	 */
	abstract protected function populateData();

	/**
	 * Returns the pivot configs object for the current class.
	 */
	protected function getPivotConfig()
	{
		$class = stripClassNamespace(get_called_class());
		return \App\QuickReports\PivotTables\Configs::getInstance($class);
	}

}