# -*- coding: utf-8 -*-
from django.conf import settings
if settings.DATABASE_ENGINE=='pool':
    settings.DATABASE_ENGINE=settings.POOL_DATABASE_ENGINE

from django.core.management.base import BaseCommand, CommandError
import os
import time
import sys
import datetime
from mysite.utils import get_option


class Command(BaseCommand):
    option_list = BaseCommand.option_list + ()
    help = "Automatic calculate attdance"
    args = ''

    def handle(self, *args, **options):
        from mysite.att.models import att_autocal_log
        if settings.ATT_CALCULATE_NEW:
            from mysite.att.calculate import auto_calculate
        else:
            from mysite.iclock.attcalc import auto_calculate
        import time
        
        # auto_calculate(True)
        logs = att_autocal_log.objects.all().order_by("-cal_date")
        if logs:
            yesterday = logs[0].cal_date
        else:
            yesterday = datetime.datetime.now().date() + datetime.timedelta(days=-1)
        while True:
            try:   
                calculate_all=False
                t_now=datetime.datetime.now()
                calculate_hour = 2
                calculate_minute = 0
                if get_option('USE_EMAIL_SERVICE'):
                    from base.email_setting import get_cfg_options
                    cfg = get_cfg_options()
                    send_time = cfg['send_time']
                    hour, minute = send_time.split(':')
                    calculate_hour = int(hour) #考勤自动计算完成后发送邮件时间
                    calculate_minute = int(minute) #考勤自动计算完成后发送邮件时间
                if t_now.date()> yesterday and t_now.hour == calculate_hour and t_now.minute == calculate_minute:#
                    calculate_all=True
                    yesterday=t_now.date()
                auto_calculate(calculate_all)
                time.sleep(5)
            except:
                time.sleep(30)
                import traceback;traceback.print_exc()
        #send_msg()
            
