<?php

class custom_code_editor extends \FileRun\Files\Plugin {

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

	function init() {

		$this->JSconfig = [
			"title" => self::t("Text Editor"),
			'iconCls' => 'fa-file-text-o',
			'useWith' => ['code', 'txt', 'csv', 'noext', 'url'],
			"popup" => true,
			"createNew" => [
				"title" => self::t("Text File"),
				"options" => [
					[
						'fileName' => self::t('New Text File.txt'),
						'title' => self::t('Plain Text'),
						'iconCls' => 'fa-file-text-o'
					],
					[
						'fileName' => 'readme.md',
						'title' => self::t('Markdown'),
						'icon' => 'images/icons/markdown.svg'
					],
					[
						'fileName' => '',
						'title' => self::t('Other..'),
						'iconCls' => 'fa-file-text-o'
					]
				]
			],
			"requiredUserPerms" => ["download"],
			'requires' => ['download']
		];
	}

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

	function saveChanges($opts = []) {
		$contents = $_POST['textContents'];
		$charset = $_POST['charset'];
		if ($charset != 'UTF-8') {
			$contents = \S::convertEncoding($contents, 'UTF-8', $charset);
		}
		$opts['source'] = 'string';
		$opts['contents'] = $contents;
		$this->writeFile($opts);
		jsonFeedback(true, 'File successfully saved');
	}

	function createBlankFile() {
		$_POST['textContents'] = '';
		$_POST['charset'] = 'UTF-8';
		$fileName = $_POST['fileName'];
		$this->data['relativePath'] = gluePath($this->data['relativePath'], $fileName);
		$this->saveChanges(['preventOverwrite' => true]);
	}
}