<?php
use \FileRun\Files;
use \FileRun\Files\Actions\Write\Write;
use \League\Csv;

class custom_csv_editor extends Files\Plugin {

	public bool $weblinksCompatible = true;
	static $localeSection = "Custom Actions: CSV Editor";
	static $publicMethods = ['saveChanges', 'loadFileData', 'thumb'];

	function init() {

		$this->JSconfig = [
			"title" => self::t('Simple Spreadsheet Editor'),
			'iconCls' => 'fa-file-csv',
			'useWith' => ['csv'],
			"popup" => true,
			"createNew" => [
				"title" => self::t('Simple Spreadsheet'),
				'defaultFileName' => self::t('New Simple Spreadsheet.csv'),
				'iconCls' => 'fa-file-csv'
			],
			"requiredUserPerms" => ['preview'],
			'requires' => ['preview']
		];
	}

	function run() {
		if ($this->isLimitedPreview()) {
			$this->centeredThumb();
			return;
		}
		require $this->path."/display.php";
	}

	function loadFileData() {
		$fp = $this->readFile(['returnFilePointer' => true]);
		$csv = \FileRun\Ext\League\Csv\Reader::createFromStream($fp);
		$csv->addUTF8StreamFilter();
		$csv->output($this->data['fileName']);
	}

	function saveChanges($opts = []) {
		$data = $this->prepareWrite($opts);

		if ($data['folder']) {return false;}
		$data['logging'] = $this->prepareLoggingDetails();
		$rs = Write::onBeforeWrite($data, 'string');
		if (!$rs) {
			self::outputError(Write::getError());
			return false;
		}
		$csv = Csv\Writer::createFromPath($data['fullPath'], 'ab');
		$extension = \FM::getExtension($this->data['fileName']);

		$csv->setDelimiter(self::getDelimiterByExt($extension));
		if ($_POST['csvHeaders']) {
			$headers = json_decode($_POST['csvHeaders']);
			if (is_array($headers)) {
				$csv->insertAll([$headers]);
			}
		}
		if ($_POST['textContents']) {
			$contents = json_decode($_POST['textContents'], true);
			if (is_array($contents)) {
				$csv->insertAll($contents);
			}
		}
		Write::onAfterWrite($data);
		jsonFeedback(true, 'File successfully saved');
	}

	function createBlankFile() {
		$_POST['csvHeaders'] = json_encode(['A', 'B']);
		$_POST['textContents'] = json_encode([['',''],['','']]);
		$fileName = \S::fromHTML($_POST['fileName']);
		$this->data['relativePath'] = gluePath($this->data['relativePath'], $fileName);
		$this->saveChanges(['preventOverwrite' => true]);
	}

	static function getDelimiterByExt($ext): string {
		return $ext == 'tsv' ? "\t" : ',';
	}
}