# All the Courses related methods

# Python
from django.utils import timezone
from datetime import datetime
from datetime import timedelta
import time
from django.db import IntegrityError
import uuid
from django.conf import settings

from utils import myqueue

from matplotlib import path

import django_rq
queue = django_rq.get_queue('default')
queuelow = django_rq.get_queue('low')
queuehigh = django_rq.get_queue('low')

from rowers.models import (
    Rower, Workout,
    GeoPoint,GeoPolygon, GeoCourse,
    )

# low level methods
class InvalidTrajectoryError(Exception):
    def __init__(self,value):
	self.value=value

    def __str__(self):
	return repr(self.value)

def polygon_to_path(polygon):
    points = GeoPoint.objects.filter(polygon==polygon).order_by(order_in_polygon)
    s = []
    for point in points:
        s.append([point.latitude,point.longitude])

    p = path.Path(np.array(s))

    return p

def coordinate_in_polygon(latitude,longitude, polygon):
    p = polygon_to_path(polygon)

    retun p.contains_points([(latitude,longitude)])[0]


    
def time_in_polygon(df,polygon,maxmin='max'):
    # df has timestamp, latitude, longitude
    p = polygon_to_path(polygon)

    latitude = df.latitude
    longitude = df.longitude

    f = lambda x: coordinate_in_polygon(x['latitude'],x['longitude'],polygon)
    
    df['inpolygon'] = df.apply(f,axis=1)

    mask = df['inpolygon'] == True

    if df[mask].empty():
        raise InvalidTrajectoryError
    
    if maxmin == 'max':
        time = df[mask]['time'].max()
    else:
        time = df[mask]['time'].min()

    
    return time
