import os
import sys
import numpy as np

from kdquery import Tree

from .index import create_dat_file
from .datatypes import dtypes
from .datapaths import paths
from .utils import pre_order, degree_to_int
from .download import completion_bar


def node_to_tuple(node):
    longitude, latitude = node.point

    limit_left = node.region[0][0]
    limit_right = node.region[0][1]
    limit_bottom = node.region[1][0]
    limit_top = node.region[1][1]

    left = node.left if node.left is not None else -1
    right = node.right if node.right is not None else -1

    return (longitude, latitude, limit_left, limit_right, limit_bottom,
            limit_top, node.axis, left, right, node.data)


def create_kdtree():
    table = np.memmap(paths['localisation'], dtype=dtypes['localisation'])
    indices = np.argsort(table, order='longitude').astype('int32')

    limits = [[degree_to_int(-62), degree_to_int(55)],
              [degree_to_int(-22), degree_to_int(52)]]

    tree = Tree(2, len(table), limits)

    count, n_total = 0, len(table)
    for i in pre_order(len(table)):
        index = indices[i]
        loc = table[index]
        tree.insert((loc['longitude'], loc['latitude']), index)

        count += 1
        completion_bar('Loading kd-tree', (count / n_total))

    print('\nStoring ...')
    tuple_list = [node_to_tuple(node) for node in tree]
    create_dat_file(tuple_list, paths['kdtree'], dtypes['kdtree'])
    print('Activation successfully')
    return True

@@ -4,21 +4,10 @@
 ort 
-os%0Aimport sys
+gc
 %0Aimp
@@ -255,189 +255,8 @@
 e):%0A
-    longitude, latitude = node.point%0A%0A    limit_left = node.region%5B0%5D%5B0%5D%0A    limit_right = node.region%5B0%5D%5B1%5D%0A    limit_bottom = node.region%5B1%5D%5B0%5D%0A    limit_top = node.region%5B1%5D%5B1%5D%0A%0A
     
@@ -378,92 +378,80 @@
 urn 
-(longitude, latitude, limit_left, limit_right, limit_bottom,%0A            limit_top, 
+node.point + tuple(node.region%5B0%5D) + tuple(node.region%5B1%5D) + %5C%0A        (
 node
@@ -575,24 +575,46 @@
 lisation'%5D)%0A
+    size = len(table)%0A
     indices 
@@ -799,26 +799,20 @@
 Tree(2, 
-len(table)
+size
 , limits
@@ -838,26 +838,20 @@
 al = 0, 
-len(table)
+size
 %0A    for
@@ -866,26 +866,20 @@
 e_order(
-len(table)
+size
 ):%0A     
@@ -1011,16 +1011,71 @@
 nt += 1%0A
+        if count %25 30000 == 0 or count == n_total:%0A    
         
@@ -1155,16 +1155,17 @@
 g ...')%0A
+%0A
     tupl
@@ -1212,16 +1212,48 @@
 n tree%5D%0A
+%0A    del tree%0A    gc.collect()%0A%0A
     crea
@@ -1315,44 +1315,8 @@
 '%5D)%0A
-    print('Activation successfully')
 %0A   

Update kdtree instatiation script