#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    demeter service
    name:device.py 处理设备
    author:rabin
"""
from demeter.core import *
from demeter.mqtt import *
class Device(object):
	type_info = []
	# 新增网关时，增加状态和电源
	def upGatewayStatus(self, farm_id, gateway_id, hardware_id):
		if hardware_id and gateway_id > 0:
			info = Demeter.service('common').list('device_info', search={'hardware_id':hardware_id})
			if not info:
				# 网关状态
				insert = {}
				insert['farm_id'] = farm_id
				insert['name'] = '网关状态'
				insert['hardware_id'] = hardware_id
				insert['gateway_id'] = gateway_id
				insert['hardware_type'] = 5
				insert['value'] = '2'
				insert['type_id'] = 0
				insert['status'] = False
				Demeter.service('common').update('device_info', None, insert)

				# 电源
				insert = {}
				insert['farm_id'] = farm_id
				insert['name'] = '电源状态'
				insert['hardware_id'] = hardware_id
				insert['gateway_id'] = gateway_id
				insert['hardware_type'] = 4
				insert['value'] = '0'
				insert['type_id'] = 8
				insert['status'] = False
				Demeter.service('common').update('device_info', None, insert)
			
	# 批量处理开关
	def switchMul(self, value):
		if value['devices']:
			model = Demeter.model('device_info')
			value['devices'] = tuple(eval(value['devices']))
			if value['oper'] == 1:
				switch = 1
			else:
				switch = 2
			for v in value['devices']:
				self.switch(v, switch)

	# 处理开关-向设备发送请求
	def switch(self, device_id, switch=1, mul=False, queue=False):
		model = Demeter.model('device_info')
		model.id = device_id
		info = model.select(type='fetchone')
		# 如果有批量控制，还要保存mul的id
		if mul:
			queue_model = Demeter.model('device_mul_queue')
			queue_model.mul_id = mul
			queue_model.device_id = info['id']
			queue_model.status = 1
			queue_model.value = switch
			if info['inorder']:
				queue_model.inorder = info['inorder']
			else:
				queue_model.inorder = 100
			queue_model.udate = info['udate']
			queue_model.hardware_id = info['hardware_id']
			queue_model.insert()
			return
		
		if info and info['status'] == True:
			"""
			if queue:
				oper = self.msg(info['type_id'], switch)
				queue_model = Demeter.model('device_mul_queue')
				queue_model.id = queue
				queue_model.update(oper='正在' + oper + info['name'])
			"""
			# 设置为loading状态,cxnum保存当前的值
			model.id = device_id
			model.update(exp='-1', cxnum=switch, oper=True, operdate=Demeter.time())

			model = Demeter.model('device_gateway')
			model.id = info['gateway_id']
			gateway_info = model.select(type='fetchone')

			if info['type_id'] > 0:
				model = Demeter.model('device_type')
				model.id = info['type_id']
				type_info = model.select(type='fetchone')
				if type_info:
					info['hardware_id'] = str(info['hardware_id'])
					switch = str(switch)
					gateway_info['hardware_id'] = str(gateway_info['hardware_id'])
					# 这里要向服务器发送pub请求了,暂时使用临时文件代替
					#Demeter.temp(key=type_info['key'], name=info['hardware_id'], value=switch)
					#pub
					pub = Pub()
					key = type_info['key'] + '/' + gateway_info['hardware_id']  + '/' + info['hardware_id']
					update = 'update/' + key
					feedback = 'status/' + key
					value = switch
					#pub.push(update, value, qos=0, callback=self.switchAction, param={'info':info, 'key':feedback, 'switch':switch}, feedback=True)
					pub.push(update, value)
		else:
			msg = self.notice('offline')
			model.id = device_id
			model.update(exp=msg, cxnum=switch, oper=True, operdate=Demeter.time())
			self.mul(info, info['name'] + '失败:' + msg, False)
			#Demeter.error('offline')

	# 处理开关-响应
	def switchAction(self, param, client, userdata, mid, msg='ok'):
		info = param['info']
		if info and info['status'] == True:
			param['switch'] = info['cxnum']
			model = Demeter.model('device_gateway')
			model.id = info['gateway_id']
			gateway = model.select(type='fetchone')

			if msg == 'ok':
				model = Demeter.model('device_info')
				model.id = info['id']
				model.update(value=param['switch'], exp='1', oper=False, operdate=Demeter.time())

				# 如果有批量控制
				self.mul(info, info['name'] + '成功', True)
			else:
				msg = self.notice(msg)
				model = Demeter.model('device_info')
				model.id = info['id']
				model.update(exp=msg, oper=True, operdate=Demeter.time())

				# 如果有批量控制
				self.mul(info, info['name'] + '失败:' + msg, False)
				oper = self.msg(info['type_id'], param['switch'])
				content = oper + gateway['name'] + '下的'+ info['name'] + '失败，错误提示：' + msg
				Demeter.service('record').msg(info['id'], content, info['farm_id'], 3)

				#Demeter.error(msg)

	def notice(self, msg):
		model = Demeter.model('notice_type')
		model.key = msg
		info = model.select(type='fetchone')
		if info:
			msg = info['name']
		return msg

	def msg(self, type_id, switch):
		oper = ''
		type_model = Demeter.model('device_type')
		type_model.id = type_id
		type_info = type_model.select(type='fetchone')
		if type_info['unit'] == 'button':
			if switch == 1:
				oper = '升起'
			elif switch == 2:
				oper = '降下'
			elif switch == 5:
				oper = '停止'
		else:
			if switch == 1:
				oper = '开启'
			else:
				oper = '关闭'
		return oper

	def mul(self, info, msg, state):
		model = Demeter.model('device_mul_queue')
		mul_model = Demeter.model('device_mul')
		model.device_id = info['id']
		model.status = 1
		queue = model.select()

		if queue:
			for v in queue:
				model.status = 1
				model.device_id = info['id']
				oper = self.msg(info['type_id'], v['value']) + msg
			if state:
				model.update(status=2, oper=oper, operdate=Demeter.time())
			else:
				model.update(status=3, oper=oper, operdate=Demeter.time())
