# -*- coding: utf-8 -*-
"""
    demeter web
    name:admin.py
    author:rabin
"""
import time
from demeter.core import *
timeSleep = 10

# 批量控制的队列 这块有点乱，但时间太紧，只有两天时间，以后改造优化
class Queue(object):

	def run(self):
		self.handle()
		time.sleep(timeSleep)

	def handle(self):
		mul_model = Demeter.model('device_mul')
		device_model = Demeter.model('device_info')
		model = Demeter.model('device_mul_queue')

		model.status = 1
		data = model.select(type='fetchone', order='inorder asc,udate asc,hardware_id asc')
		service = Demeter.service('device')

		# 查看当前有没有正在执行的设备，如果有，不能继续执行了
		msg = service.notice('timeout')
		device_model.oper = True
		device_model.exp.nq(msg)
		device_model.hardware_type = 3
		device = device_model.select(type='fetchone')

		if not device and data and not data['operstate']:
			service.switch(data['device_id'], switch=data['value'], mul=False, queue=data['id'])
			model.id = data['id']
			model.update(operstate=True)
			#mul_model.id = data['mul_id']
			#mul_model.update(oper='')

		# 将执行完成的进行清理
		mul_model.oper.nq('')
		data = mul_model.select()
		if data:
			for v in data:
				devicesNum = len(tuple(eval(v['devices'])))
				model.status.ins((2,3))
				cur = Demeter.time() - 10
				model.operdate.assgin(cur, '<=')
				queue = model.select()
				num = len(queue)
				if num == devicesNum:
					errorNum = 0
					model.mul_id = v['id']
					model.update(status=4)
					for qv in queue:
						if qv['status'] == 3:
							errorNum = errorNum + 1
					mul_model.id = v['id']
					if errorNum == devicesNum:
						mul_model.update(oper='', value=v['old'])
					else:
						mul_model.update(oper='')