<?php
class UserSetting extends DBObject {	
	public function __construct(User $user, $key) {
		parent::__construct("user_settings", array("user_id", "key"), array($user->UserId, $key));
		if (!$this->UserId)
			$this->UserId=$user->UserId;
		if (!$this->Key)
			$this->Key=$key;
		
		$this->Value=$this->GetValue();
		unset($this->_changedFields['Value']);
	}

	private function GetValue(){
		switch ($this->Type){
			case DataTypes::Integer:
				return (int)$this->Value;
			case DataTypes::Float:
				return (float)$this->Value;
			case DataTypes::Boolean:
				return (bool)$this->Value;
			case DataTypes::String:
				return (string)$this->Value;
			case DataTypes::Collection:
			case DataTypes::Object:
				return json_decode($this->Value);
		}
		return null;
	}
	
	public function Save() {	
		if (!$this->HasChangedFields())
			return;
		
		switch (gettype($this->Value)){
			case "integer":
				$this->Type=DataTypes::Integer;
				break;
			case "double":
				$this->Type=DataTypes::Float;
				break;
			case "boolean":
				$this->Type=DataTypes::Boolean;
				break;
			case "string":
				$this->Type=DataTypes::String;
				break;
			case "Array":
				$this->Type=DataTypes::Collection;
				$this->Value=json_encode($this->Value);
				break;
			case "object":
				$this->Type=DataTypes::Object;
				$this->Value=json_encode($this->Value);
				break;
			default:
				$this->Type=DataTypes::Null;
		}
		
		parent::Save();
	}
}
