<?php
class ServerModel extends DBModel {
	public $_name = VODCMS_SERVER;
	public $PrintPage;
	public function init(){
		
	}
	public function add($POST){
		if (is_array($POST)){
			if ( empty($POST['name'])){
				$this->error = _('请填写服务器名称!');
				return false;
			}
			$license = $GLOBALS['license'];
			if ($license['edition'] == 'Free'){
				if (count($this->getList()) >= 5){
					$this->error = _('免费吧只允许添加5个服务器');
					$this->_DB->update(VODCMS_SERVER, array('locked'=>1), array('locked'=>0));
					$this->_DB->update(VODCMS_SERVER, array('locked'=>0), 'locked=1 order by sid desc limit 5');
					return false;
				}
			}
			systemlog::set(_('添加了名称为'.$POST['name'].'的服务器'));
			return $this->_DB->insert($this->_name, $POST);
		}else{
			$this->error = _('传入Server:Add方法不正确!');
			return false;
		}
		
	}
	/*
	修改服务器资料
	*/
	public function modify($POST){
		if (is_array($POST)){
			if ( empty($POST['name'])){
				$this->error = _('请填写服务器名称!');
				return false;
			}
			systemlog::set(_('编辑名称为'.$POST['name'].'的服务器'));
			return $this->_DB->update($this->_name, $POST, 'sid='.$POST['sid']);
		}else{
			$this->error = _('传入Server:Add方法不正确!');
			return false;
		}
	}
	/*
	删除
	*/
	public function delete($id){
		systemlog::set(_('删除编号为'.$id.'的服务器'));
		return $this->_DB->delete($this->_name, 'sid='.$id);
	}
	public function getAll($where=null){
		$data = null;
		$select = $this->_DB->select();
		$sql = $select->from($this->_name)->where($where)->order('sid DESC')->toString();
		$all = $this->_DB->fetAll($sql);
		//echo $sql;
		foreach($all as $val){
			if($val['parentid'] == 0){
				$data[$val['sid']]['self'] = $val;
			}else{
				$data[$val['parentid']]['nodes'][] = $val;
			}
		}
		return $data;
	}
	public function getList($where=null){
		$select = $this->_DB->select();
		$sql = $select->from($this->_name)->where($where)->order('sid DESC')->toString();
		return $this->_DB->fetAll($sql);
	}
	public function getRow($sid){
		$select = $this->_DB->select();
		$sql = $select->from($this->_name)->where('sid='.$sid)->order('sid DESC')->toString();
		return $this->_DB->fetRow($sql);
	}
	public function CreateOption($id=0, $parentid=0){
		$select = $this->_DB->select();
		$data = '';
		$sql = $select->from($this->_name)->where('locked=0 AND parentid='.$parentid)->order('sid DESC')->toString();
		$all = $this->_DB->fetAll($sql);
		foreach ($all as $row){
			if ($id == $row['sid']){
				$data.= '<option value="'.$row['sid'].'" selected="selected" >'.$row['name'].'</option>';
			}else{
				$data.= '<option value="'.$row['sid'].'" >'.$row['name'].'</option>';
			}
		}
		unset($all, $sql);
		return $data;
	}
	/*
	反转服务器状态
	*/
	public function locked($id){
		$sql = 'UPDATE '.VODCMS_SERVER.' SET locked = NOT(locked) WHERE sid='.$id;
		$this->_DB->Exec($sql);
		$sql = "UPDATE ".VODCMS_MOVIE." SET locked = NOT(locked) WHERE find_in_set($id, `sid`)";
		$num = $this->_DB->Exec($sql);
		systemlog::set(_('反转编号为'.$id.'的服务器.同时影响力'.$num.'部影片'));
		return false;
	}
}