#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    demeter service
    name:record.py 用于记录设备过来的数据
    author:rabin
"""
from demeter.core import *
import json
import time
class Record(object):

	def topic(self, key):
		array = key.split('/')
		slen = len(array)
		if slen >= 4:
			return {'method':array[0], 'type':array[1], 'parent':array[2], 'child':array[3]}
		else:
			return {'method':array[0], 'type':array[1], 'parent':array[2], 'child':array[2]}

	def push(self, key, value):
		value = value.replace("b'", '')
		value = value.replace("'", '')
		config = self.topic(key)
		method = 'record_' + config['method']
		cls = Demeter.service(method, 'mqtt')
		state = False
		if config['method'] != 'pic':
			if '{' in value:
				value = Demeter.isJson(value)
				if value:
					state = True
					for k,v in value.items():
						config['child'] = k
						cls.handle(self, config, v)
		if state == False:
			cls.handle(self, config, value)

	def save(self, config, value, name='', device_type=None):
		Demeter.service('device').save(config,value, name, device_type)