import json
import os.path

# Medialab Prado
medialab_prado = [ -3.69380, 40.41041 ]
# X 441133.28
# Y 4473541.39


# Plaza del Sol
# Top left corner of the search field
plaza_del_sol = [  -3.7035, 40.41684 ]
# X 440315.95
# Y 4474261.62

# Atocha Renfe
# Bottom right corner of the search field
atocha_renfe = [ -3.6886, 40.40697 ]
# X 441571.52
# Y 4473156.10

# Return true if the tree lives within the given bounding box
# and it has a street address in the database
def within (bbox):
  def eligible (tree):
    coords = tree['geometry']['coordinates']
    if bbox[0][0] <= coords[0] <= bbox[1][0] \
      and bbox[0][1] <= coords[1] <= bbox[1][1] \
      and tree['properties']['MINTDIRECCIONAUX'] is not None:
      return True


    return False 

  return eligible

# Load trees from the selected_ordered_trees
# who live within barrio de las letras
# and have a postal address recorded in the database 
def load_trees_from_json():
  basepath = os.path.dirname(__file__)
  datafile = os.path.join(basepath, '../data/selected_trees_ordered.geojson')

  barrio_de_las_letras = [
    [-3.7025, 40.4134],
    [-3.6945, 40.4169]
  ]

  with open(datafile, 'r') as fp: 
    data = json.load(fp)
    trees = data['features']
    return list(filter(within(barrio_de_las_letras), trees))
    

if __name__ == '__main__':
  from random import shuffle

  eligible_trees = load_trees_from_json()
  print(len(eligible_trees))
  shuffle(eligible_trees)
  print(eligible_trees[:1])
