import os
import pandas as pd

from shsplots.matplotlib.plot_context import PlotContext
from shsplots.matplotlib.histogram import plot_histogram

from prolothar_queue_mining.model.job import Job

dataset_directory = 'experiments/datasets/call_center/'

def load_raw_dataframe():
    maxcol = 17

    #months to read
    # months = ["january","february","march","april","may","june","july","august","september","october","november","december"]
    months = ["august"]
    mapOfMonthData = {}

    mapOfPandaMonthData = {}


    for eachMonth in months:
        #open file
        with open(f'{dataset_directory}/raw_months/{eachMonth}.txt', 'r') as dataset:
            count = 0

            mapofcolms = {}
            mapofindextocol = {}

            for line in dataset:

                    line = line.strip("\n")
                    #if not first line store the data
                    #eachrow is list
                    eachrow = line.split("\t")

                    if count ==0 :
                        #initilization of code.
                        indexcounterofcol = 0
                        for clmname in eachrow:
                            mapofcolms[clmname] = []
                            mapofindextocol[indexcounterofcol] = clmname
                            indexcounterofcol = indexcounterofcol + 1
                    else:
                        #validation that, list size is equal to maxcol
                        listCount = 0
                        if len(eachrow) == maxcol :
                            #nice data
                            for eachElement in eachrow :
                                clmName = mapofindextocol[listCount]
                                mapofcolms[clmName].append(eachElement)
                                listCount = listCount + 1
                    count = count + 1
            mapOfMonthData[eachMonth] = mapofcolms
            mapOfPandaMonthData[eachMonth] = pd.DataFrame((mapofcolms))

    return pd.concat(mapOfPandaMonthData.values())

if __name__ == '__main__':
    df = load_raw_dataframe()
    df = df[df['outcome'] == 'AGENT']
    df['ser_time'] = df['ser_time'].astype(int)
    df = df[df['ser_time'] > 30]
    df = df[(df['type'] == 'PS') | (df['type'] == 'PE')]
    df['service_start'] = pd.to_datetime(df['date'] + ' ' + df['ser_start'])
    df['arrival'] = pd.to_datetime(df['date'] + ' ' + df['vru_exit'])
    df['arrival'] = df[['arrival', 'service_start']].min(axis=1)
    df['weekday'] = df['arrival'].dt.day_name()
    df['hour'] = df['arrival'].dt.hour
    df['departure'] = pd.to_datetime(df['date'] + ' ' + df['ser_exit'])
    #handle calls that go beyond midnight
    df.loc[df['departure'] < df['arrival'], 'departure'] += pd.Timedelta(days=1)

    min_arrival_date = min(df['arrival'])
    df['arrival'] = (df['arrival'] - min_arrival_date).dt.total_seconds()
    df['departure'] = (df['departure'] - min_arrival_date).dt.total_seconds()
    df['job'] = df.apply(lambda row: Job(
        row['vru+line'] + ' ' + row['call_id'],
        {'priority': row.priority, 'weekday': row.weekday, 'hour': row.hour}), axis=1)

    observed_arrivals = []
    observed_departures = []
    waiting_times_dict = {}
    with open(os.path.join(dataset_directory, 'jobs.txt'), 'w', encoding='utf-8') as f:
        for row in df.itertuples():
            observed_arrivals.append((row.job, int(row.arrival)))
            observed_departures.append((row.job, int(row.departure)))
            waiting_times_dict[row.job] = int(row.q_time)
            f.write(str(row.job))
            f.write('\n')

    observed_arrivals.sort(key=lambda x: x[1])
    observed_departures.sort(key=lambda x: x[1])

    with open(os.path.join(dataset_directory, 'arrivals.txt'), 'w', encoding='utf-8') as f:
        for job, arrival_time in observed_arrivals:
            f.write(f'{arrival_time};{job.job_id}\n')
    with open(os.path.join(dataset_directory, 'departures.txt'), 'w', encoding='utf-8') as f:
        for job, departure_time in observed_departures:
            f.write(f'{departure_time};{job.job_id}\n')
    with open(os.path.join(dataset_directory, 'waiting_times.txt'), 'w', encoding='utf-8') as f:
        for job, waiting_time in waiting_times_dict.items():
            f.write(f'{job.job_id};{waiting_time}\n')
