# -*- coding: utf-8 -*-
"""
Created on Wed Jul 25 12:39:56 2018

@author: hanye
"""

import datetime
import argparse
import sys
import re
import task_stats
from func_cal_weekly_net_inc import cal_weekly_net_inc_with_doc_type_name_multi_thread
from func_cal_weekly_net_inc import parse_week_param
from func_find_week_num import find_week_belongs_to
from func_update_weekly_datapool import define_doc_type
from func_find_week_num import day_by_week_info
from func_find_week_num import find_first_day_for_given_start_weekday

def get_weekly_doc_type_name_by_week_str(week_str):
    weekly_doc_type = 'daily-url-%s' % week_str
    parse_week = parse_week_param(weekly_doc_type)
    if parse_week is None:
        print('Illegal input week_str: %s' % week_str)
        return None
    else:
        return weekly_doc_type

week_day_start = 1
todayT = datetime.datetime.today()

parser = argparse.ArgumentParser()
parser.add_argument('-w', '--week_str', type=str, default=None, help=('like 2018_w25_s1'))
parser.add_argument('-m', '--cal_for_missed', default='0')
parser.add_argument('-t', '--threads_num', default=None)
args = parser.parse_args()

if args.cal_for_missed == '1':
    print('Will calculate for missed data, whose field of "weekly_cal_base" '
          'is absent.')
    query_term = {
        "must_not": [
            {"exists": {"field": "weekly_cal_base"}}
        ]
    }
else:
    query_term = None
week_day_start = 1
def week_start_day(week_year, week_no,week_day, week_day_start=1):
    year_week_start = find_first_day_for_given_start_weekday(week_year, week_day_start)
    week_start = year_week_start + datetime.timedelta(days=(week_no-1)*7)
    return week_start

if args.week_str is None:
    seven_days_ago_T = todayT - datetime.timedelta(days=7)
    week_year, week_no, week_day = find_week_belongs_to(seven_days_ago_T,
                                                        week_day_start)
    week_start = day_by_week_info(week_year,week_no,week_day)
    week_start = week_start_day(week_year,week_no,week_day)
    nowT_qingbo = week_start + datetime.timedelta(days=7)
    nowT_feihua = week_start + datetime.timedelta(days=6)
    weekly_doc_type_name = define_doc_type(week_year, week_no,
                                           week_day_start=week_day_start)
    
else:
    weekly_doc_type_name = get_weekly_doc_type_name_by_week_str(args.week_str)
    p = re.compile(r'\d+')
    week_mess = p.findall(args.week_str)
    week_year = int(week_mess[0])
    week_no = int(week_mess[1])
    week_day = int(week_mess[2])
    week_start = week_start_day(week_year,week_no,week_day)
    nowT_qingbo = week_start + datetime.timedelta(days=7)
    nowT_feihua = week_start + datetime.timedelta(days=6)
    if weekly_doc_type_name is None:
        print('Failed to parse week info from input argument: %s, '
              'program exits.' % args.week_str)
        sys.exit('cal_weekly_net_inc_auto_task - '
                 'Program exits dure to illegal input week_str')
    else:
        pass
dayT = datetime.datetime(nowT_qingbo.year, nowT_qingbo.month, nowT_qingbo.day)
day_str_tody = dayT.isoformat()[:10]
dayT_ye = datetime.datetime(nowT_feihua.year, nowT_feihua.month, nowT_feihua.day)
day_str_ye = dayT_ye.isoformat()[:10]
time_of_processed_data_T = datetime.datetime(nowT_qingbo.year, nowT_qingbo.month, nowT_qingbo.day)
index = 'short-video-weekly'
pre_task_names = {
    'write_qingbo_TK_ATU_data_from_ftp_daily_task':
        {'days_str_of_proc_data': day_str_tody},
    'write_fh_data_from_ftp_call_func_daily_task00':
        {'days_str_of_proc_data': day_str_ye},
    }
print (pre_task_names, weekly_doc_type_name)
index = 'short-video-weekly'
if args.threads_num is not None:
    try:
        threads_num = int(args.threads_num)
    except ValueError:
        print('Illegal value for argument threads_num: %s' % args.threads_num)
else:
    threads_num = 10
task_stats.wait_for_pre_task_to_cal(
    pre_task_names, loggerName=None,
    cal_func=cal_weekly_net_inc_with_doc_type_name_multi_thread,
    # must be (dayT, ) rather than (dayT). (dayT) would be considered as
    # dayT which is not an iterable, cannot be dispatched by *args
    cal_func_params=(weekly_doc_type_name, ),
    cal_func_kwargs={'index_weekly': index, 'threads_num':threads_num},
    task_name='cal_weekly_net_inc_weekly__task',
    program_file_name='cal_weekly_net_inc_weekly__task.py',
    task_freq='weekly',
    time_of_processed_data_T=time_of_processed_data_T
    )

