from kivy_garden.mapview import MapView
from kivy.clock import Clock
from kivy.app import App

from treemarker import TreeMarker

class ForestMapView(MapView):
    get_trees_timer = None
    tree_names = []
    
    def print_current_zoom(self, *args):
        print("] Zoom level: " + str(self.zoom))
    
    def start_get_fov_trees(self):
        # After one second get the trees in field of view
        try:
            self.get_trees_timer.cancel()
        except:
            pass
        
        self.get_trees_timer = Clock.schedule_once(self.get_fov_trees, 1)
        
    def get_fov_trees(self, *args):
        # Get reference to main app and the db cursor
        app = App.get_running_app()
        # Gebug gps position
        print("] Current map position: " + str(self.get_bbox()))
        min_lat, min_lon, max_lat, max_lon = self.get_bbox()
        sql_statement = "SELECT * FROM locations WHERE x > %s AND x < %s AND y > %s AND y < %s" % (min_lat, max_lat, min_lon, max_lon)       #sql_statement = "SELECT * FROM locations"
        app.cursor.execute(sql_statement)
        trees = app.cursor.fetchall()
        for tree in trees:
            name = tree[0]
            print("] Fountain detected: " + str(tree))
            if name in self.tree_names:
                continue
            else:
                self.add_tree(tree)
    
    def add_tree(self, tree):
        # Create TreeMarker
        lat, lon = tree[20], tree[21]
        treemarker = TreeMarker(lat=lat, lon=lon)
        treemarker.tree_data = treemarker
        
        # Add TreeMarker to the map
        self.add_widget(treemarker)
        
        # Keep track of the TreeMarker's name
        name = tree[1]
        self.tree_names.append(name)
