#!/usr/bin/python3

import argparse
import glob
import os
# import numpy
# import matplotlib.pyplot as plt
from datetime import datetime

from erimp import Erimp
# import graphs
import shotiser
import filer
import dater
from folda import Folda
from gruti import Gruti

parser = argparse.ArgumentParser(description='smoothed report counter')
parser.add_argument('-v', action='store_true', help='raise verbosity')
parser.add_argument('bapis', metavar='bnp', type=str, nargs='+',
                    help='bits and pieces arguments')
args = parser.parse_args()
e = Erimp(args.bapis, do_verbose=args.v)
folda = Folda(e)
gruti = Gruti(e)
six_weeks = 42 * 24 * 60 * 60


# # a counter how many issues a report had


# # to move to folder / folders
def get_shoti(fufi):
    bana = os.path.basename(fufi)
    if bana[10:11] != '_':
        print('bad ' + fufi)
        return None
    shoti = bana[11:17]
    return shoti


def get_window(array, end_count, frame):
    out = []
    end_value = array[end_count]
    out.append(end_value)
    count = end_count
    while count > -1:
        array_count = array[count]
        # print('count ' + str(count) + ' ' + str(array_count))
        if end_value - array_count > frame:
            # print('out of frame')
            break
        out.append(array_count)
        count = count - 1
    return out

# repcode_issues = {}
# def add_issue(repcode, fufi):
#    if repcode not in repcode_issues:
#        repcode_issues[repcode] = []
#    if len(repcode_issues[repcode]) == 6:
#           return
#    repcode_issues[repcode].append(fufi)


def populate(the_list, the_dict):
    out = {}
    for item in the_list:
        out[item] = the_dict[item]
    return out


def get_max_issuedate(tist_fufis):
    max_issuedate = None
    for tist in tist_fufis:
        fufi = tist_fufis[tist]
        issuedate = filer.get_issuedate(fufi)
        if max_issuedate is None or max_issuedate < issuedate:
            max_issuedate = issuedate
    return max_issuedate


def filter_by_issuedate(tist_fufis, max_issuedate, max_diff):
    keys = list(tist_fufis)
    for tist in keys:
        fufi = tist_fufis[tist]
        issuedate = filer.get_issuedate(fufi)
        # print(issuedate + ' ' + max_issuedate)
        diff = dater.diff(issuedate, max_issuedate)
        if diff <= max_diff:
            continue
        # print("I cut " + tist_fufis[tist])
        del tist_fufis[tist]
    return tist_fufis


def eval_count(tist_fufis):
    count_of_repcodes = {}
    for tist in tist_fufis:
        tist_fufi = tist_fufis[tist]
        parts = tist_fufi.split('/')
        repcode = parts[-3]
        if repcode not in count_of_repcodes:
            count_of_repcodes[repcode] = 1
            continue
        count_of_repcodes[repcode] += 1
    return len(count_of_repcodes)


def eval_by_six(tist_fufis):
    count_of_repcodes = {}
    for tist in tist_fufis:
        tist_fufi = tist_fufis[tist]
        parts = tist_fufi.split('/')
        repcode = parts[-3]
        if repcode not in count_of_repcodes:
            count_of_repcodes[repcode] = 1
            continue
        count_of_repcodes[repcode] += 1
    total = 0
    for repcode in count_of_repcodes:
        if count_of_repcodes[repcode] > 6:
            count_of_repcodes[repcode] = 6
        total += count_of_repcodes[repcode] / 6
    return total


def show_window(tist_fufis):
    for tist in tist_fufis:
        fufi = tist_fufis[tist]
        time = datetime.utcfromtimestamp(tist).strftime('%Y-%m-%d %H:%M:%S')
        print(time + ' ' + fufi)


do_verbose = args.v
shoti_fufis = {}
for rep_fudi in glob.glob(e.dirs['reports'] + '/*'):
    repcode = os.path.basename(rep_fudi)
    sent_fudi = rep_fudi + '/sent/'
    if not os.path.isdir(sent_fudi):
        if do_verbose:
            print(f"no sent for {repcode}")
        continue
    firsts = folda.firsts(sent_fudi)
    for issuedate in firsts:
        fufi = firsts[issuedate]
        shoti = get_shoti(fufi)
        if shoti in shoti_fufis:
            if do_verbose:
                print(fufi + ' ' + shoti_fufis[shoti])
        shoti_fufis[shoti] = fufi
        continue
tist_fufis = {}
shotis_fufis = dict(sorted(shoti_fufis.items()))
for shoti in shotis_fufis:
    tist = shotiser.ekam(shoti)
    tist_fufis[tist] = shotis_fufis[shoti]

# print(tist_fufis)
list_tists = list(tist_fufis)

total_tists = len(list_tists)
count = 0
values = {}
while count < total_tists:
    the_window = get_window(list_tists, count, six_weeks)
    tist = the_window[0]
    the_window = populate(the_window, tist_fufis)
    max_issuedate = get_max_issuedate(the_window)
    # print(max_issuedate)
    count += 1
    # time = datetime.utcfromtimestamp(tist).strftime('%Y-%m-%d %H:%M:%S')
    # print(time)
    # show_window(the_window)
    # continue
    # # not used any mare
    # the_window = filter_by_issuedate(the_window, max_issuedate, 41)
    # print(count)
    # show_window(the_window)
    # continue
    # print(the_window)
    value = eval_by_six(the_window)
    values[tist] = value
# quit()

# # debug
# for tist in values:
#    time = datetime.utcfromtimestamp(tist).strftime('%Y-%m-%d %H:%M:%S')
#    print(time + ' ' + str(values[tist]))

gruti.by_repis_time(values, 'smoothed_report_count')
