# -*- coding: utf-8 -*-
from django.conf import settings
if settings.DATABASE_ENGINE=='pool':
    settings.DATABASE_ENGINE=settings.POOL_DATABASE_ENGINE
from django.utils.translation import ugettext_lazy as _
from django.core.management.base import BaseCommand, CommandError
import sys
import datetime
import time
import os
import shutil
from traceback import print_exc
from django.utils.simplejson import dumps
from mysite import settings
from django.core.cache import cache
import shutil

        
class Command(BaseCommand):
    option_list = BaseCommand.option_list + ()
    help = "Starts zksaas adms ."
    args = ''

    def handle(self, *args, **options):
        import time,os
        from attrec_update import line_to_log, att_deal_logger
        from base.sync_api import SYNC_MODEL
        from comm.att.struct.sync_action import get_att_record_file
        record_bak_path = 'MoleSys/data_store/error_records/'
        store_path = "MoleSys/data_store/att_rec/"
        if not os.path.exists(record_bak_path):
            os.makedirs(record_bak_path)
        if SYNC_MODEL:
            from base.backup import get_attsite_file
            batch_lens = 100 # 最多插入的批次，根据服务器的配置以及数据库的性能来配置条数的多少
            cnts = get_attsite_file()["SYS"]["SQL_BATCH_CNTS"]
            if cnts:
                batch_lens = int(cnts)
            while True:
                dev,lines,file = get_att_record_file()
                if lines:
                    lens = len(lines)
                    times = lens%batch_lens == 0 and lens/batch_lens or (lens/batch_lens + 1)
                    for i in range(times):
                        m_lines = lines[i*batch_lens:(i+1)*batch_lens]
                        succcess = True
                        try:
                            while succcess:
                                ret = line_to_log(dev,m_lines,event="files") # ret =False <数据库断开了>
                                if not ret:
                                    time.sleep(60*2)
                                else:
                                    succcess = False
                            time.sleep(0.1)
                        except Exception, e:
                            # import shutil
                            if file:
                                filename = file.split('/')[-1]
                                shutil.copyfile(file, record_bak_path+filename)
                                att_deal_logger('%s --> %s' % (filename, e))
                            break
                    if file:
                        os.remove(file)
                    else:
                        cache_file = cache.get('analysis_file')
                        if cache_file:
                            shutil.copyfile(store_path + cache_file, record_bak_path+cache_file)
                            att_deal_logger('Analysis error file: %s' % cache_file)
                            os.remove(store_path + cache_file)
                    cache.set('analysis_file', '')
                time.sleep(0.1)
