#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os, sys
sys.path.append(os.path.abspath(os.path.dirname(os.path.abspath(__file__))+"/../scripts"))

import fileinput
import numpy as np
import matplotlib as mpl

show = len(sys.argv) > 1 and sys.argv[1] == 'show'
if not show:
	mpl.use('pgf')

import matplotlib.pyplot as plt
import matplotlib.lines as lines
from common import set_size, config_plt

config_plt()


def loadData(fn):
	xs = []
	ys = []
	content = []

	cst = 0
	inf = 0
	sup = 0

	with open(fn) as f:
		cst, inf, sup = [float(x) for x in f.readline().split(',')]
		content = f.readlines()

	for line in content:
		tok = line.split(',')
		xs.append(float(tok[0]))
		ys.append(float(tok[1]))

	return [[cst, inf, sup], xs, ys]


def drawLine(plt, b, e, label, color):
	x = np.arange(b, e, 1)
	plt.plot(x, x, label=label, color=color);

def drawHLine(plt, b, e, v, color):
	x = np.arange(b, e, 1)
	plt.plot(x, [v]*(e-b), color=color);

def drawCloud(plt, data, label, color):
	x, y = data
	plt.scatter(x, y, label=label, s=3, linewidth=0)


def figCores(n, lblA, lblB):
	name = 'fig'+str(n)

	fig = plt.figure()

	data = loadData('plot_data/'+name+'a')
	cst, inf, sup = data[0]

	#  plt.title(u"nombre de cœurs fixe = " + str(int(cst)))
	plt.xlabel(u'tâches')
	plt.ylabel(u'PRNG')

	drawLine(plt, inf, sup, u"sans optimisation", 'red')
	drawCloud(plt, data[1:], lblA, 'blue')

	data = loadData('plot_data/'+name+'b')
	drawCloud(plt, data[1:], lblB, 'green')

	fig.set_size_inches(set_size(455.24408, .8))

	fig.legend()

	if not show:
		fig.savefig('plots/'+name+'.pdf', format='pdf', bbox_inches='tight')
	return plt


def figTasks(n):
	name = 'fig'+str(n)

	fig = plt.figure()
	width = 3.487
	height = width/1.618

	data = loadData('plot_data/'+name+'a')
	cst, inf, sup = data[0]

	plt.title(u"nombre de tâches fixe = " + str(int(cst)))
	plt.xlabel(u'cœurs')
	plt.ylabel(u'PRNG')

	drawCloud(plt, data[1:], 'equilibrated distribution', 'blue')

	data = loadData('plot_data/'+name+'b')
	drawCloud(plt, data[1:], 'greedy distribution', 'green')

	fig.set_size_inches(set_size(455.24408, .8))

	fig.legend()

	if not show:
		fig.savefig('plots/'+name+'.pdf', format='pdf', bbox_inches='tight')
	return plt


def fig1():
	return figCores(1, u"politique d'exécution 1", u"politique d'exécution 2")

def fig2():
	return figCores(2, u"politique d'exécution 1", u"politique d'exécution 2")

def fig3():
	return figCores(3, u"$\mathbf{T} = \{1, 2, 3, 4, 5, 6, ..., 64\}$", u"$\mathbf{T} = \{1, 2, 4, 8, 16, 32, 64\}$")

def fig4():
	return figTasks(4)

def fig5():
	return figTasks(5)

def fig6():
	return figTasks(6)


plts = []

plts.append(fig1())
plts.append(fig2())
plts.append(fig3())
plts.append(fig4())
plts.append(fig5())
plts.append(fig6())

if show:
	for plt in plts:
		plt.show()
