import numpy as np
import matplotlib.pyplot as plt
import psycopg2
from matplotlib.animation import FuncAnimation

connection = psycopg2.connect(user = "heikki",
                              password = "",
                            host = "localhost",
                              port = "5432",
                              database = "postgres")

cursor = connection.cursor()
# Print PostgreSQL Connection properties
print ( connection.get_dsn_parameters(),"\n")

# Print PostgreSQL version
cursor.execute("SELECT p[0] as x, p[1] as y FROM points ORDER BY point_zorder(p);")

xall = []
yall = []

colors = plt.cm.jet(np.linspace(0,1,5))

batchsize = 200

boxes = []

batchno = 0
tuples = cursor.fetchmany(batchsize)
while tuples:

    xthis = []
    ythis = []
    for t in tuples:
        xthis.append(t[0])
        ythis.append(t[1])
        xall.append(t[0])
        yall.append(t[1])

    xmin = min(xthis)
    xmax = max(xthis)
    ymin = min(ythis)
    ymax = max(ythis)

    boxes.append((xmin, xmax, ymin, ymax))

    tuples = cursor.fetchmany(batchsize)

    batchno = batchno + 1


cursor.close()
connection.close()

fig, ax = plt.subplots()

boxlines = []
for i in range(len(boxes)):
    boxplot, = plt.plot([], [])
    boxlines.append(boxplot)

points, = plt.plot([], [])
    
def update(num):

    points.set_data(xall[0:num], yall[0:num])

    if (num % batchsize) == 0:
        boxno = int(num / batchsize)
        box = boxes[boxno]
        xmin = box[0]
        xmax = box[1]
        ymin = box[2]
        ymax = box[3]

        boxlines[boxno].set_data([xmin, xmin, xmax, xmax, xmin], [ymin, ymax, ymax, ymin, ymin])
        return boxlines[boxno], points,
    else:
        return points,

ax.set_xlim(-100, 100)
ax.set_ylim(-100, 100)

ani = FuncAnimation(fig, update, len(xall), interval=10)

#ani.save('/tmp/zorder.mp4')

plt.show()



