<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS\module\codemirror
 * @copyright Copyright (c) 2014 - 2016 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * codemirrorSettings Class
 *
 * Class to implement settings for CodeMirror editor.
 *
 * @package clearFusionCMS\module\codemirror
 */
class codemirrorSettings implements cfModuleSettingsInterface {

	/**
	 * Get a list of settings groups.
	 *
	 * @return array Array of setting groups, name => func name
	 */
	function getSettingsGroups() {
		if(!clearFusionCMS::getUser()->hasPermission('cfCodeMirror.settings'))
			return array();

		return array(
			__('Features', 'codemirrorBackend') => 'features'
		);
	}

	/**
	 * Implement feature settings.
	 *
	 * @param flForm $form The form object to use.
	 * @param flDb $db The database object.
	 * @return bool true if the settings were updated, false if failed to update or null if no change.
	 */
	function featuresSetting($form, $db) {
		if(!clearFusionCMS::getUser()->hasPermission('cfCodeMirror.settings'))
			return null;

		$cfg = clearFusionCMS::getSiteConfig('cfCodeMirror');

		$themes = array('' => __('[default]', 'codemirrorBackend'));
		foreach(glob(FLMODPATH . 'codemirror/scripts/theme/*.css') as $f) {
			$themes[basename($f, '.css')] = basename($f, '.css');
		}

		$theme = new flFormElementSelect($form, 'theme', $cfg->get('theme', ''), $themes);
		$theme->setLabel(__('Editor Color Theme', 'codemirrorBackend'));

		$alwaysWrap = new flFormElementCheckbox($form, 'alwaysWrap', $cfg->get('alwaysWrap', true));
		$alwaysWrap->setLabel(__('Wrap Long Lines', 'codemirrorBackend'));

		$submit = new flFormElementSubmit($form, 'update');
		$submit->setCaption(__('Update Settings', 'codemirrorBackend'))->setCSS('primary');

		$form->groupElements('submit', array($submit), new flFormDecoratorList(new flFormDecoratorDl()));
		$form->focusElement($theme);

		if($form->isSubmitted() && $form->isValid()) {
			cfSettingsAudit::update(
				__('CodeMirror', 'codemirrorBackend'),
				__('Features', 'codemirrorBackend'),
				[
					'theme' => $cfg->get('theme'),
					'alwaysWrap' => $cfg->get('alwaysWrap')
				]
			);

			$cfg->theme = $theme->getValue();
			$cfg->alwaysWrap = $alwaysWrap->getValue();

			return true;
		}

		return null;
	}
}
