import json
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import functools

from scipy import stats
from os import walk
from pylab import *

abr_algo_types = ["Bola - E", "Dynamic", "Throughput"]
network_profiles = ["PROFILE_CASCADE", "PROFILE_INTRA_CASCADE", "PROFILE_SPIKE", "PROFILE_SLOW_JITTERS", "PROFILE_FAST_JITTERS"]

def t_test(a, b, alpha = 0.05):
	t, p = stats.ttest_ind(b, a)
	if(p/2 < alpha and t > 0):
		return True
	else:
		return False
		
def rank_using_t_test(bola_e_values, throughput_values, dynamic_values):
	answer_dict = {}

	answer_dict['Bola'] = 0
	answer_dict['Throughput'] = 0
	answer_dict['Dynamic'] = 0

	if t_test(bola_e_values, throughput_values):
		answer_dict['Bola'] = answer_dict['Bola'] + 1
	else:
		answer_dict['Throughput'] = answer_dict['Throughput'] + 1
		
	if t_test(throughput_values, dynamic_values):
		answer_dict['Throughput'] = answer_dict['Throughput'] + 1
	else:
		answer_dict['Dynamic'] = answer_dict['Dynamic'] + 1
		
	if t_test(bola_e_values, dynamic_values):
		answer_dict['Bola'] = answer_dict['Bola'] + 1
	else:
		answer_dict['Dynamic'] = answer_dict['Dynamic'] + 1

	
	print(" > ".join(dict(sorted(answer_dict.items(), key=lambda item: item[1])).keys()))
	print("")

def plot_cdf(a, abr_algo_type):
	x = np.sort(a)
	y = np.arange(len(x))/float(len(x))
	plt.plot(x, y, label=abr_algo_type)
	plt.legend(loc="upper left")
	plt.ylim(-1.5, 2.0)
	
def analyse_stall_duration(data_set):
	print("\n------------Analysing Stall Durations-----------\n")
	for network_profile in network_profiles:
		print("Network profile:", network_profile)
		

		ax = data_set[['profile', 'abr_algo_type', 'stall_duration']].loc[data_set['profile'] == network_profile].boxplot(by = 'abr_algo_type')
		
		ax.set_title('Network profile ' + network_profile)
		ax.set_xlabel('ABR Algorithms')
		ax.set_ylabel('Stall Duration')
		
		df = data_set.loc[data_set['profile'] == network_profile]
		
		a = df.loc[df['abr_algo_type'] == 'Bola - E'].stall_duration.to_numpy()
		b = df.loc[df['abr_algo_type'] == 'Throughput'].stall_duration.to_numpy()
		c = df.loc[df['abr_algo_type'] == 'Dynamic'].stall_duration.to_numpy()
		
		#plot_cdf(a, 'Bola - E');
		#plot_cdf(b, 'Throughput');
		#plot_cdf(c, 'Dynamic');
		
		#plt.xlabel("Stalling Time")
		#plt.ylabel("CDF of Stalling Time")
		#plt.title("CDF of Stalling Time in network condition " + network_profile)
		
		gg = []
		
		gg.append(a.mean())
		gg.append(b.mean())
		gg.append(c.mean())
		
		print("BOLA - E :", a.mean(), "Throughput:", b.mean(), "Dynamic:", c.mean())
		print(np.diff(gg) / np.abs(gg[:-1]) * 100)
		plt.show()
		
		#rank_using_t_test(a, b, c)
		
	print("------------------------------------------------\n")
	
def analyse_average_latency(data_set):
	print("\n------------Analysing Average Latency-----------\n")
	for network_profile in network_profiles:
		print("Network profile:", network_profile)
		
		ax = data_set[['profile', 'abr_algo_type', 'average_latency']].loc[data_set['profile'] == network_profile].boxplot(by = 'abr_algo_type')
		
		ax.set_title('Network profile ' + network_profile)
		ax.set_xlabel('ABR Algorithms')
		ax.set_ylabel('Average Latency')
		
		df = data_set.loc[data_set['profile'] == network_profile]
		
		a = df.loc[df['abr_algo_type'] == 'Bola - E'].average_latency.to_numpy()
		b = df.loc[df['abr_algo_type'] == 'Throughput'].average_latency.to_numpy()
		c = df.loc[df['abr_algo_type'] == 'Dynamic'].average_latency.to_numpy()
		
		#plot_cdf(a, 'Bola - E');
		#plot_cdf(b, 'Throughput');
		#plot_cdf(c, 'Dynamic');
		
		#plt.xlabel("Average Latency")
		#plt.ylabel("CDF of Average Latency")
		#plt.title("CDF of Stalling Time in network condition " + network_profile)
		
		gg = []
		
		gg.append(a.mean())
		gg.append(b.mean())
		gg.append(c.mean())
		
		print("BOLA - E :", a.mean(), "Throughput:", b.mean(), "Dynamic:", c.mean())
		print(np.diff(gg) / np.abs(gg[:-1]) * 100)
		plt.show()
		
		#rank_using_t_test(a, b, c)
		
	print("------------------------------------------------\n")
	
def analyse_average_bitrate(data_set):
	print("\n------------Analysing Average Bit rate-----------\n")
	for network_profile in network_profiles:
		print("Network profile:", network_profile)
		
		ax = data_set[['profile', 'abr_algo_type', 'average_bitrate']].loc[data_set['profile'] == network_profile].boxplot(by = 'abr_algo_type')
		
		ax.set_title('Network profile ' + network_profile)
		ax.set_xlabel('ABR Algorithms')
		ax.set_ylabel('Average Bitrate')
		
		df = data_set.loc[data_set['profile'] == network_profile]
		
		a = df.loc[df['abr_algo_type'] == 'Bola - E'].average_latency.to_numpy()
		b = df.loc[df['abr_algo_type'] == 'Throughput'].average_latency.to_numpy()
		c = df.loc[df['abr_algo_type'] == 'Dynamic'].average_latency.to_numpy()
		
		rank_using_t_test(a, b, c)
		
	print("------------------------------------------------\n")
	
def analyze(data_set):
	#analyse_stall_duration(data_set)
	analyse_average_latency(data_set)
	#analyse_average_bitrate(data_set)
	
	

result_dir = './Final_Results'

abr_algo_type_list = []
profile_list = []

data_set = pd.DataFrame()

stall_duration_list = []
average_latency_list = []
average_buffer_length_list = []
average_bitrate_list = []
num_switches_list = []

for abr_algo in abr_algo_types:
	for network_profile in network_profiles:
		latency_list_for_runs = []
		path = result_dir + '/' + abr_algo + '/' + network_profile
		
		for f in os.listdir(path):
			_json = open(path + '/' + f)
			data = json.load(_json)
			abr_algo_type_list.append(abr_algo)
			profile_list.append(network_profile)
			stall_duration_list.append(data["stallDuration"])
			average_latency_list.append(data["averageLatency"])
			average_buffer_length_list.append(data["averageBufferLength"])
			average_bitrate_list.append(data["averageBitrate"])
			num_switches_list.append(data["numSwitches"])
			
			
data_set['abr_algo_type'] = abr_algo_type_list
data_set['profile'] = profile_list
data_set['stall_duration'] = stall_duration_list
data_set['average_latency'] = average_latency_list
data_set['average_buffer_length'] = average_buffer_length_list
data_set['average_bitrate'] = average_bitrate_list
data_set['num_switches'] = num_switches_list

#print(data_set)

#analyze(data_set)

testt = {}

for abr_algo in abr_algo_types:
	qoefile_path = result_dir + '/' + abr_algo + '/qoe.json'
	_json = open(qoefile_path)
	data = json.load(_json)
	aut = list(data.values())
	testt[abr_algo] = sum(aut) / len(aut)
	
	
plt.xlabel("ABR Algorithms")
plt.ylabel("QoE score")
	
plt.bar(*zip(*testt.items()))
plt.show()	
#plt.show()

