<?php

namespace App\ReportsData\ChangesQueue\Entity;

class CurrencyRate extends \App\ReportsData\ChangesQueue\GeneralAbstract
{

	/**
	 * The original table name (the actual entity).
	 * @var string
	 */
	protected $originalDbTableName;

	/**
	 * The PK column name (usually "id").
	 * @var string
	 */
	protected $originalPkColumnName = 'date';

	/**
	 * Returns the original table name that stores the original rows.
	 * @return string
	 */
	protected function getOriginalDbTableName()
	{
		global $DBTCurrencyMarkets;
		return $DBTCurrencyMarkets;
	}


	/**
	 * Adds all records for the currency exchange rates (also deletes the existing records for this entity).
	 */
	public function resync()
	{

		// check if inside a transaction
		if (!\DB::isInsideTransaction()) {
			throw new \Exception('You must be inside a transaction in order to call '.__METHOD__);
		}

		global $DBTRdQueueMain;

		$db = \DB::getInstance();

		// delete existing rows
		$deleteAllSQL = "DELETE FROM `$DBTRdQueueMain` WHERE entity = ?";
		$deleteAllEx = $db->Execute($deleteAllSQL, [$this->entity]);
		if (!$deleteAllEx) {
			throw new \DBException('Invalid SQL for deleting existing RD records in the queue when resync().');
		}

		// insert all currency dates
		$insertAllSQL = "INSERT INTO `$DBTRdQueueMain` (entity, id, addTime) SELECT 'CurrencyRate', `date`, '".time()."' FROM `{$this->originalDbTableName}` GROUP BY `date`";
		$insertAllEx = $db->Execute($insertAllSQL);
		if (!$insertAllEx) {
			throw new \DBException('Invalid SQL for inserting existing RD records in the queue when resync().');
		}

	}

}

