<?php

namespace App\Reports\Generation;

class WriteFile
{

	/**
	 * The current generation object - stores all information needed for the actual report DB table
	 * population.
	 * @var Generate
	 */
	private \App\Reports\Generation\Generate $reportGeneration;


	public function __construct(\App\Reports\Generation\Generate $reportGeneration)
	{
		$this->reportGeneration = $reportGeneration;
	}


	public function write() :void
	{

		switch ($this->reportGeneration->format) {

			case 'xlsx': {

				$writeReportFile = new \App\Reports\Generation\WriteFile\Xlsx();
				break;
			}

			default: {
				throw new \Exception("Invalid/missing format for report output `{$this->reportGeneration->format}`.");
			}

		}

		// copy main information from generation class to the writing one
		$writeReportFile->dbTable		= $this->reportGeneration->getTableManager()->getTableName();
		$writeReportFile->columns		= $this->getOrderedColumnsNames();
		$writeReportFile->locationDir	= $this->reportGeneration->getLocationDir();
		$writeReportFile->fileName		= $this->reportGeneration->fileName;

		$writeReportFile->process();

	}


	/**
	 * Returns the list of columns that
	 * @return array
	 */
	public function getOrderedColumnsNames() :array
	{

		$finalColumnsList = [];

		$stdCols = $this->reportGeneration->stdColumns;
		$custCols = [];
		foreach ($this->reportGeneration->customColumns as $custColCode=>$colDet) {
			if (!key_exists('hidden', $colDet) or !$colDet['hidden']) {
				$custCols[$custColCode] = $colDet['name'];
			}
		}

		foreach($this->reportGeneration->columnsOrder as $colCode) {
			if (key_exists($colCode, $stdCols)) {
				$finalColumnsList[$colCode] = $stdCols[$colCode];
				unset($stdCols[$colCode]);
			} elseif (key_exists($colCode, $custCols)) {
				$finalColumnsList[$colCode] = $custCols[$colCode];
				unset($custCols[$colCode]);
			} // if an invalid element is found in the list, it is ignored, we do not throw any error
		}

		// add the rest of the standard and custom columns
		$finalColumnsList = $finalColumnsList + $stdCols + $custCols;

		return $finalColumnsList;
	}


}
