#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    demeter service
    name:record_pic.py 处理摄像头的图片数据
    author:rabin
    key:pic/图片名_图片总数_当前序号/gateway/device
"""
import time
import json
import uuid
from datetime import *
from demeter.core import *
class Record_pic(object):
	pic = {}
	def handle(self, record, config, value):
		self.record = record
		method = config['type'].split('_')
		name = method[0] + '.jpg'
		if name not in self.pic:
			self.pic[name] = {}
		total = int(method[1])
		index = int(method[2])
		self.pic[name][index] = value
		picLen = len(self.pic[name])
		if picLen >= total:
			self.create(name, config)

	def create(self, name, config):
		pic = sorted(self.pic[name].items(), key=lambda e:e[0], reverse=False)
		data = []
		day = str(date.today())
		day = day.split('-')
		file_name =  str(uuid.uuid5(uuid.uuid1(), 'file'))
		file_path = day[0] + '/' + day[1] + '/' + day[2]
		file_path = File.mkdirs(os.path.join(Demeter.path, 'runtime','camera', file_path)) + '/' + Demeter.md5(file_name) + '.jpg'

		for value in pic:
			data.append(value[1])
		with open(file_path, 'wb') as f:
			f.writelines(data)
			del self.pic[name]
		file_path = file_path.replace(Demeter.path + 'runtime', '')
		self.record.save(config, file_path, name)