<?php
/*
 * Copyright (c) 2013, webvariants GbR, http://www.webvariants.de
 *
 * This file is released under the terms of the MIT license. You can find the
 * complete text in the attached LICENSE file or online at:
 *
 * http://www.opensource.org/licenses/mit-license.php
 */

class _WV8_Setting extends WV_Property {
	protected $namespace;  ///< string   Namespace-Angabe
	protected $isLocal;    ///< boolean  wenn true, wird die Einstellung auch auf der Platte ausgelagert
	protected $pagename;   ///< string   Seitenname für die Backend-UI
	protected $group;      ///< string   Gruppe

	public function __construct($name, array $data) {
		parent::__construct($name, $data);

		// name is given as "namespace.subnamespace.name" -- so let's split it up

		$lastDot = strrpos($name, '.');

		if ($lastDot === false) {
			$namespace = 'project';
		}
		else {
			$namespace = substr($name, 0, $lastDot);
			$name      = substr($name, $lastDot + 1);
		}

		$this->name      = $name;
		$this->namespace = $namespace;
		$this->isLocal   = $this->getData('local', false);
		$this->group     = $this->getData('group', '');
		$this->pagename  = $this->getData('pagename', 'translate:wv8_title_user_settings');
	}

	public function renderAsFormElement(sly_Form $form) {
		if ($this->getData('multilingual_only', false) && !sly_Util_Language::isMultilingual()) {
			return $form;
		}

		$values = WV8_Settings::getValue($this->namespace, $this->name, null, WV_Sally::CLANG_ALL, true);
		return $this->renderForm($form, $values);
	}

	public function getValue($clang = null) {
		return WV8_Settings::getValue($this->namespace, $this->name, null, $clang, false);
	}

	public function getValues($raw = false) {
		return WV8_Settings::getValue($this->namespace, $this->name, null, WV_Sally::CLANG_ALL, $raw);
	}

	public function isLocal()      { return $this->isLocal;   }
	public function getNamespace() { return $this->namespace; }
	public function getPagename()  { return $this->pagename;  }
	public function getGroup()     { return $this->group;     }

	public function getID() {
		return WV8_Settings::hash($this->namespace.'.'.$this->name);
	}

	public function getGroupID() {
		return WV8_Settings::hash($this->pagename.'.'.$this->group);
	}

	public function setValue($value, $clang) {
		if (!sly_Util_Language::exists($clang)) {
			throw new WV8_Exception('Language does not exist.');
		}

		$this->values[$clang] = $value;
		return true;
	}
}
