#!/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):

	# 新增网关时，增加状态和电源
	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'] = '0'
				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 = 0
			for v in value['devices']:
				self.switch(v, switch)

	# 处理开关-向设备发送请求
	def switch(self, device_id, switch=1, mul=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.insert()
		if info and info['status'] == True:
			# 设置为loading状态,cxnum保存当前的值
			model.id = device_id
			model.update(exp='-1', cxnum=switch)

			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)
			self.mul(info['id'], info['type_id'], info['name'], switch, '失败:' + 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')

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

				# 如果有批量控制
				self.mul(info['id'], info['type_id'], info['name'], param['switch'], '失败:' + msg, False)

				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 mul(self, id, type_id, name, switch, msg, state):
		model = Demeter.model('device_mul_queue')
		model.device_id = id
		queue = model.select()
		if queue:
			if state:
				model.device_id = id
				model.delete()
			model = Demeter.model('device_mul')
			if msg:
				for v in queue:
					model.id = v['mul_id']
					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 = '关闭'
					oper = oper + name + msg
					model.update(oper=oper)