# -*- coding: utf-8 -*-
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
import os
import time
import sys
import thread
import datetime
from ooredis.client  import get_client
from ooredis import *
from mysite.utils import get_option
def adms_butt_handler():
    from mysite.personnel.models.model_emp import format_pin,device_pin
    r_client = get_client()
    batch = int(get_option("BUTT_ADMS_BUTT_BATCH"))
    key_list = r_client.keys("butt_emp_info:*:*")[0:batch]
    butt_list = []
    for k in key_list:
        butt_dict={}
        dict_val = Dict(k)
        butt_dict['empPin'] = format_pin(dict_val.get('pin'))
        butt_dict['bioData'] = dict_val.get('template')
        butt_dict['bioType'] = dict_val.get('biotype')
        butt_dict['generateTime'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        butt_dict['templateNo'] = dict_val.get('templateno')
        butt_dict['version'] = dict_val.get('fpversion')
        if dict_val.get('valid'):
            butt_dict['validType'] = dict_val.get('valid')
        butt_list.append(butt_dict)
    
    
    from mysite.inbiobutt.adms_butt import add_adms_bio_template 
    if len(butt_list) >0:
        ret = add_adms_bio_template(butt_list)
        
        fail_list = ret.get("fail") or []
        success_list = ret.get("success") or []
        if len(success_list) > 0:
            for su in success_list:
                emp_pin = device_pin(su.get("empPin"))
                temp_id = su.get("templateNo")
                temp_type = su.get("bioType")
                if temp_type =="1":
                    t_type = "fg"
                else:
                    t_type = "face"
                r_d = Dict("butt_emp_info:%s:%s|%s"%(emp_pin,temp_id,t_type))
                r_d.delete()
                print "r_d===============",r_d
        if ret.has_key("req_fail"):
            print "req_fail============",ret["req_fail"]
        if len(fail_list)>0:
            print "fail_list===========",len(fail_list)
    #        for err in fail_list.items():
    #            print u"人员编号:%s,失败原因:%s"%(err[0],dir_error.get(err[1]))
        #			    insert_records=[i for i in insert_records if ''.join(i.get(badgenumber_key)) not in fail_list.keys()]
        if len(success_list)==0:
            print "len(success_list)=============",len(success_list)
        
        print len(butt_list)
		

class Command(BaseCommand):
    option_list = BaseCommand.option_list + ()
    help = "Starts adms butt inbio process."
    args = ''
    
    def handle(self, *args, **options):
            last_clean = datetime.datetime.now()
            while True:
                now = datetime.datetime.now()
                adms_butt_handler()
                time.sleep(1)
			
