import cv2
import dlib
import numpy as np

from matplotlib import pyplot as plt

#from scipy.cluster.hierarchy import dendrogram, linkage, fcluster, fclusterdata, leaders

import scipy as sp
import time
import os
import shutil as sh
import glob
import openface
import subprocess

#propia
import utils
import vector_face as vecFace 
import clustering 

#Saber resolucio de la pantalla
def screen_size():
    size = (None, None)
    args = ["xrandr", "-q", "-d", ":0"]
    proc = subprocess.Popen(args,stdout=subprocess.PIPE)
    for line in proc.stdout:
        if isinstance(line, bytes):
            line = line.decode("utf-8")
            if "Screen" in line:
                size = (int(line.split()[7]),  int(line.split()[9][:-1]))
    return size

# Grafica per mostrar les persones
def graficaPersones(vecImg, vecFile, div = 100):
    ni = len(vecImg[0])
    nf = len(vecFile[0])
    
    xValors = [i for i in range(0,nf)]

    tipoLinea = ('k-.','c-.','m-.','b-.','r-.','k-.')
    tipoPunto = ('go','bo','ro','mo','ko','co')
    tipoBase =  ('b-','c-','m-','b-','r-','k-')
    
    r,h = screen_size()
    if r is None:
        sizeFig = (80,80)
    else:
        sizeFig = (int(r/75),int(h/75))
    
    fig = plt.figure(u'Grafica Persones localitzades en '+ str(ni) + ' Imatges', figsize = sizeFig, dpi=80)
    
    if ni > 799:
        div = 200
           
    #plt.title(u'Persones localitzades')  # Colocamos el titulo del grafico
    #plt.xlabel('Temps en imatges')  # Colocamos la etiqueta en el eje x
    #plt.ylabel('Cares')  # Colocamos la etiqueta en el eje y
    
    for ii in range(0,int(nf/div)+1):
    #for ii in range(0,int(1)):
        plt.subplot(int('24'+str(ii+1)))
        plt.title('De ' + str(ii*div) + ' fins ' + str(div*(ii+1)) + ' imatges')  # Colocamos el titulo del grafico
        i=0
        
        for vec in vecFile:
            plt.stem(xValors, vec, linefmt='r-.', markerfmt=tipoPunto[i], basefmt=tipoBase[i])  # Dibuixar els valors
            i += 1
            
        i = 0
        maxValorI = 0
        for vec in vecImg:
            if maxValorI < max(vec):
                maxValorI = max(vec)
            plt.stem(xValors, vec, linefmt='b', markerfmt=tipoPunto[i], basefmt=tipoBase[i])  # Dibuixar els valors
            i += 1
            
        maxValor = 0
        for xi in xValors[ii*div:div*(ii+1)]:
            for vec in vecFile:
                if vec[xi] != -1:
                    if maxValor < max(vec[ii*div:div*(ii+1)]):
                        maxValor = max(vec[ii*div:div*(ii+1)])
                    plt.text(xi-0.05, vec[xi]+0.1, str(vec[xi]), fontsize = 10)
        
        plt.xlabel('Temps en imatges')  # Colocamos la etiqueta en el eje x
        plt.ylabel('Cares')  # Colocamos la etiqueta en el eje y
        plt.xlim(ii*div,div*(ii+1))
        plt.ylim(-0.10,max((maxValor,maxValorI))+1)
        plt.grid(True)
    
    plt.show()

def graficaPaso(vecImg,vecFile):
    ni = len(vecImg)
    nf = len(vecFile)
    
    xi = [x for x in range(0,ni)]
    xf = [x for x in range(0,nf)]
    
    yi = vecImg
    yf = vecFile
    
    r,h = screen_size()
    if r is None:
        sizeFig = (80,80)
    else:
        sizeFig = (int(r/75),int(h/75))
    
    fig = plt.figure('Grafica cares Localitzades en '+ str(ni) + ' Imatges', figsize = sizeFig, dpi=80)
    
    if ni > 799:
        ndiv = 200
    else:
        ndiv = 100
    
    for i in range(0,int(ni/ndiv)+1):
        
        plt.subplot(int('24'+str(i+1)))
        plt.title('De ' + str(i*ndiv) + ' fins ' + str(ndiv*(i+1)) + ' imatges')
        
        plt.step(xi,yi, where = 'mid' , color = 'b', linewidth = 2, label = 'Cares Detectades')
        plt.step(xf,yf, where = 'mid' , color = 'r', linestyle = '--' , linewidth = 1, label = 'Cares del Fitxer' )
        
        plt.legend(loc=1)
        
        plt.ylim(-0.25,1.25)
        plt.xlim(i*ndiv,ndiv*(i+1))
        
        plt.grid(True)
        
    plt.show()


def grafica(x,Y, etiquetes = None, color = ('r','g','b','c','m','y','k'),tipo = ('-','--','-.',':')):
    i,c,t = 0,0,0
    etiqueta = ''
    plt.figure()
    
    for y in Y:
        if etiquetes is not None:
            etiqueta = etiquetes[i]
        plt.plot(x,y,color[c]+tipo[t],label=etiqueta)
        plt.grid(True)
        i +=1
        c += 1
        if c >= len(color):
            c = 0
            t +=1
            if t >= len(tipo):
                t = 0
                
    if etiquetes is not None:
        plt.legend(loc=1)
        
    plt.show()
    
def lecFile(fitxer):
    f = open(fitxer, "r")

    retorn = []
    linea = f.readline()
    while linea != "":
        retorn.append(linea[:len(linea)-2].split(';'))
        linea = f.readline()

    f.close
    return retorn


def vecsMinMax(vectors):
    vecMin,vecMax = [],[]
    i,n = 0,len(vectors[0])
    while i < n:
        vecMax.append(max([float(x[i]) for x in vectors]))
        vecMin.append(min([float(x[i]) for x in vectors]))
        i += 1
    
    return [vecMin,vecMax]

def vecsOnes(vectors):
    
    vecs = [[1 if float(x) > 0.0 else -1 for x in rep] for rep in vectors]

    return vecs

def calcOnes(vectors):
    vecP,vecN,vecT = [],[],[]
    
    for vec in vectors:
        p = vec.count(1)
        n = vec.count(-1)
        vecP.append(p)
        vecN.append(n)
        vecT.append((p+n)/2)
        
    return [vecP,vecN,vecT]

def mainMinMax(arxiu):
    vectors = lecFile(arxiu)
    minims, maxims = vecsMinMax(vectors)
    x = range(0,len(minims))
    y = [minims,maxims]
    
    
    grafica(x,y,['Minims','Maxims'])
    
def mainOnes(arxiu):
    vectors = lecFile(arxiu)
    vecs = vecsOnes(vectors)
    x = range(0,len(vecs))
    y = calcOnes(vecs)
    
    
    grafica(x,y,['Ones Positives','Ones Negatives','Control'])
