import cv2
import numpy as np
import math
import imutils
import matplotlib.pyplot as plt

def FindContours(img):
	imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
	ret,thresh = cv2.threshold(imgray,127,255,0)
	_,contours,hierarchy = cv2.findContours(thresh, 1, 2)
	return contours

def EnhanceBrightness(frame, n):
	imgHLS = cv2.cvtColor(frame, cv2.COLOR_BGR2HLS)
	imgHLS[:,:,1] += n
	imgLight = cv2.cvtColor(imgHLS, cv2.COLOR_HLS2BGR)
	return imgLight

def Filter(lightFrame):
	kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])
	img = cv2.filter2D(lightFrame, -1, kernel)
	filtered = cv2.bilateralFilter(img, 5, 150, 150)
	return filtered

def FindArrow(frame):
	size = 0
	height, width, channels = frame.shape
	mask = np.zeros((height, width, 3), dtype = "uint8")
	contours = FindContours(frame)
	for cnt in contours:
		tmp = cv2.contourArea(cnt)
		approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, True), True)
		if len(approx) > 6 and len(approx) < 9 and tmp >  1000 and tmp < 20000:
			cv2.drawContours(mask, [cnt], 0, (255,255,255), -1)
			size = tmp
	arrows = cv2.bitwise_and(frame, mask)
	return size, arrows, mask

def FindOrientation(imgArrow):
	x = 0
	y = 0
	w = 0
	h = 0
	contours = FindContours(imgArrow)
	for cnt in contours:
		tmp = cv2.contourArea(cnt)
		M = cv2.moments(cnt)
		if tmp > 1000 :
			x,y,w,h = cv2.boundingRect(cnt)
	if x != 0:
		verticale = math.sqrt(math.pow((x-x), 2)+math.pow((y-(y+h)), 2))
		horizontale = math.sqrt(math.pow((x-(x+w)),2)+math.pow((y-y),2))
		centerCoord = (x + verticale/2, (x+w)+(horizontale/2))

		extLeft, extRight, extTop, extBot = FindExtremPoints(imgArrow)
		droite = math.sqrt(math.pow((extTop[0] - extRight[0]), 2)+math.pow((extTop[1] - extRight[1]), 2))
		gauche = math.sqrt(math.pow((extLeft[0] - extTop[0]), 2)+math.pow((extLeft[1] - extTop[1]), 2))
		haut = math.sqrt(math.pow((extTop[0] - extRight[0]), 2)+math.pow((extTop[1] - extRight[1]), 2))
		bas = math.sqrt(math.pow((extRight[0] - extBot[0]), 2)+math.pow((extRight[1] - extBot[1]), 2))
	
		if (horizontale > verticale) and (droite < gauche):
			print("droite")
			return 1
		elif (horizontale > verticale) and (gauche < droite):
			print("gauche")
			return 2
		elif (verticale > horizontale) and (haut < bas):
			print ("haut")
			return 3
		elif (verticale > horizontale) and (bas < haut):
			print ("bas")
			return 4
		else :
			print ("NULL")
			return -1
	else :
		return -1

def FindExtremPoints(imgArrow):
	imgray = cv2.cvtColor(imgArrow,cv2.COLOR_BGR2GRAY)
	ret,thresh = cv2.threshold(imgray,127,255,0)
	cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
	cnts = imutils.grab_contours(cnts)
	c = max(cnts, key=cv2.contourArea)
	extLeft = tuple(c[c[:, :, 0].argmin()][0])
	extRight = tuple(c[c[:, :, 0].argmax()][0])
	extTop = tuple(c[c[:, :, 1].argmin()][0])
	extBot = tuple(c[c[:, :, 1].argmax()][0])
	return extLeft, extRight, extTop, extBot

def Direction(image) :
	frame = imread(image)
	imgLight = EnhanceBrightness(frame, 3)
	imgFiltered = Filter(imgLight)
	imgFiltered = EnhanceBrightness(imgFiltered, 2)		
	size, imgArrows, mask = FindArrow(imgFiltered)
	orientation = FindOrientation(imgArrows)
	return orientation
