<?php
namespace App\EntityList;

class UserTraces extends GeneralMtAbstract
{
	public function __construct()
	{
		global $DBTUserTraces;
		$this->tableName = $DBTUserTraces;
		$this->tableAlias = 'userTraces';

		$this->setColumn('timestamp'); // I need to put a column here otherwise I get sql syntax error

		// run the parent
		parent::__construct();
	}

	public function getMonthTablesList(): array
	{
		$period = $this->getMonthTablesList_period(['userTraces.timestamp', 'timestamp']);

		// if no months needed - skip this step
		if ($period['startDate'] > $period['endDate']) {
			return [];
		}

		// get the list of month tables
		$userTracesMonthsList = array_keys(\App\Utils\Db\TablesUtilsCached::getInstance()->getExistingMonthTablesByInterval($this->tableName, $period['startDate'], $period['endDate']));

		return $userTracesMonthsList;
	}

	protected function getMonthTablesList_period(array $columns): array
	{
		// initialize start/end dates
		$startDate = 946684800; // min date => 2000-01-01 00:00:00
		$endDate = 16756675200; // max date => 2500-12-31 00:00:00

		// LOOP THROUGH EACH FILTER AND CHECK IF THE CURRENT COLUMN IS IN $columns ////////////////
		foreach($this->filters as $filter) {
			if (in_array($filter['fullColumn'], $columns)) {
				// greater than
				if (($filter['sign'] == ">=" || $filter['sign'] == ">") && $startDate < $filter['value']) {
					$startDate = $filter['value'];
				}

				// less than
				if (($filter['sign'] == "<=" || $filter['sign'] == "<") && $endDate > $filter['value']) {
					$endDate = $filter['value'];
				}

				// between
				if ($filter['sign'] == "BETWEEN") {
					if ($startDate < min($filter['value'])) {
						$startDate = min($filter['value']);
					}

					if ($endDate > max($filter['value'])) {
						$endDate = max($filter['value']);
					}
				}
			}
		}

		// return the limits
		return ['startDate' => \Engine\DateTime::createFromTimestamp($startDate)->formatDateIso(), 'endDate' => \Engine\DateTime::createFromTimestamp($endDate)->formatDateIso()];
	}

	/**
	 * Applys the user access restrictions.
	 * @see \App\EntityList\GeneralMtAbstract::addUserRestrictionFilter()
	 */
	protected function addUserRestrictionFilter()
	{

	}

}