from .models import *


def findCoordinates(address):
    import http.client, urllib.parse, json
    import time

    # get the start time
    st = time.time()

    #conn = http.client.HTTPConnection('api.positionstack.com')
    
    #params = urllib.parse.urlencode({
    #    'access_key': '62af7c8094ec908da7880c470beba225',
    #    'query': address,
    #    'country': 'LV',
    #    })

    #conn.request('GET', '/v1/forward?{}'.format(params))


    #res = conn.getresponse()

    #data = res.read()
    #data =  data.decode('utf-8')
    try:
        latitude = json.loads(data)['data'][0]['latitude']
        longitude = json.loads(data)['data'][0]['longitude']
    except:
        latitude = 56.512716
        longitude = 27.342739
    
    return [latitude, longitude]

def get_weather_data(meteostation):
    if meteostation.meteoservice_id == 1:
        print(Weather_WunderGround(meteostation.service_uri))
        return Weather_WunderGround(meteostation.service_uri)
    elif meteostation.meteoservice_id  == 2:
        print(Weather_Awekas(meteostation.service_uri))
        return Weather_Awekas(meteostation.service_uri)


def Weather_WunderGround(service_uri):
    import requests
    from dateutil import parser
    url = service_uri

    response = requests.get(url).json()
    location = response['observations'][0]['neighborhood']
    temperature = response['observations'][0]['metric']['temp']
    windSpeed = response['observations'][0]['metric']['windSpeed']
    windDeg = response['observations'][0]['winddir']
    precipRate = response['observations'][0]['metric']['precipRate']
    time = parser.parse( response['observations'][0]['obsTimeLocal'])

    return {
        'location' : location,
        'temperature' : temperature,
        'wind_speed' : windSpeed,
        'wind_deg' : windDeg,
        'precip_rate' : precipRate,
        'time' : time,
    }

def Weather_Awekas(service_uri):
    import requests
    from datetime import datetime
    from dateutil import parser
    url = service_uri

    response = requests.get(url).json()
    location = "Rēzekne"
    temperature = response['current']['temperature']
    windSpeed = response['current']['windspeed']
    windDeg = response['current']['winddirection']
    precipRate = response['current']['precipitation']
    time = datetime.fromtimestamp( response['current']['datatimestamp'] )

    return {
        'location' : location,
        'temperature' : temperature,
        'wind_speed' : windSpeed,
        'wind_deg' : windDeg,
        'precip_rate' : precipRate,
        'time' : time,
    }

def TreeRowGetTrees(treeRow):
    import json
    import geopy.distance

    # if there are trees in the row, delete them
    Trees.objects.filter(row_id = treeRow.id).delete()

    Treebreed = EnterpriseSpecificBreeds.objects.get(pk = treeRow.tree_breed_id)
    distance = Treebreed.planting_distance
    json = treeRow.coordinates
    coordinates = json['geometry']['coordinates']
    coords_1 = coordinates[0]
    coords_2 = coordinates[1]

    difX = coords_2[0] - coords_1[0]
    difY = coords_2[1] - coords_1[1]

    difCoords = [difX,difY]

    lengthLine = geopy.distance.geodesic(coords_1, coords_2).m
    treeOnLine = int(lengthLine / distance)

    interval_X = difX / (treeOnLine + 1)
    interval_Y = difY / (treeOnLine + 1)

    Trees.objects.create(
            latitude = coords_1[1],
            longitude = coords_1[0],
            width = Treebreed.width,
            height = Treebreed.height,
            breed = Treebreed.title,
            block_id = treeRow.block_id,
            cultivares_id = Treebreed.cultivar.id,
            row_id = treeRow.id
    )
    Trees.objects.create(
            latitude = coords_2[1],
            longitude = coords_2[0],
            width = Treebreed.width,
            height = Treebreed.height,
            breed = Treebreed.title,
            block_id = treeRow.block_id,
            cultivares_id = Treebreed.cultivar.id,
            row_id = treeRow.id
    )

    for i in range(1,treeOnLine+1):
        coord = [coords_1[0] + (interval_X * i),coords_1[1] + (interval_Y * i)]
        Trees.objects.create(
            latitude = coord[1],
            longitude = coord[0],
            width = Treebreed.width,
            height = Treebreed.height,
            breed = Treebreed.title,
            block_id = treeRow.block_id,
            cultivares_id = Treebreed.cultivar.id,
            row_id = treeRow.id
        )
