from django.db import models
import datetime
from django.utils import timezone
import math

# Create your models here.

class LocationManager(models.Manager):
    def nearby_locations(self, latitude, longitude, radius, max_results=500, use_miles=True):
        if use_miles:
            distance_unit = 3959
        else:
            distance_unit = 6371

        from django.db import connection, transaction
        from petfinder import settings
        cursor = connection.cursor()
        if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
            connection.connection.create_function('acos', 1, math.acos)
            connection.connection.create_function('cos', 1, math.cos)
            connection.connection.create_function('radians', 1, math.radians)
            connection.connection.create_function('sin', 1, math.sin)

        sql = """SELECT id, (acos(sin(radians(%f)) * sin(radians(loc_lat)) + cos(radians(%f)) * 
        cos(radians(loc_lat)) * cos(radians(%f-loc_lon))) * %d)
        AS distance FROM pets_pet WHERE distance < %f
        ORDER BY distance LIMIT 0 , %d;""" % (latitude, latitude, longitude,distance_unit, radius, max_results)
        cursor.execute(sql)
        ids = [row[0] for row in cursor.fetchall()]

        return self.filter(id__in=ids)

class Pet(models.Model):

    def __str__(self):
        return self.name

    name = models.CharField(max_length=128) #name of animal
    animal_id = models.CharField(max_length=128) #allow super-long names
    intake_at = models.DateTimeField(auto_now_add=False, blank= True, default=timezone.now)
    found_location = models.CharField(max_length=128)
    loc_lat = models.FloatField(null = True, blank= True)
    loc_lon = models.FloatField(null = True, blank= True)
    animal_type = models.CharField(max_length=128) #eg dog, cat, turtle
    breed = models.CharField(max_length=128) #allow super-long names
    color = models.CharField(max_length=96)
    intake_type = models.CharField(max_length=96) #stray, surrender, etc
    intake_condition = models.CharField(max_length=128) #normal, nursing, etc
    sex = models.CharField(max_length=128)
    age = models.CharField(max_length=128)
    outcome_at = models.DateTimeField(auto_now_add=False, blank= True, default=timezone.now)
    outcome_type = models.CharField(max_length=128)
    outcome_subtype = models.CharField(max_length=128)
    objects = LocationManager()


    def generate_image_link(self):
        image = "http://www.petharbor.com/get_image.asp?RES=Detail&ID="+self.animal_id+"&LOCATION=ASTN"
        return image

    def clean_location(self):
        location = self.found_location.replace(" in ", " ").replace(")", "").replace("(", "").replace("/", "").replace("&", "and")
        return location

    image = property(generate_image_link)
    location = property(clean_location)

