from flask import Blueprint, render_template, request, jsonify
from time import gmtime, strftime
from draw import *
from mydatabase import *
import redis
import time
import json

crozet_api = Blueprint('crozet_api', __name__)

@crozet_api.route('/crozet/', methods=['GET','POST'])
def crozet():
    print "main crozet entry"
    return render_template('crozet.html')

@crozet_api.route('/refreshcrozet/', methods=['GET','POST'])
def refreshcrozet():
    r = redis.Redis(host='127.0.0.1', port='6379')

    data = '<svg id="svg1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1800" height="1420">'

    SPACE = 14           # pixel space between boxes
    SWITCHSIZE = 1400    # pixels tall for switch box graphic
    x = 210              # starting X (across) andy (down) for heading text
    y = 10

    # draw header text
    data = data + headerText(x, y, 'Crozet')

    # start producers here. Guess where the mid should based on the total number of ports and back up from there
    m = r.get("crozetProdPorts")
    mid = int(m)*32
    y = SWITCHSIZE/2 - mid/2

    # start switch
    data = data + drawSwitchBox('black','eeeeee', 800, 10, SWITCHSIZE)

    # total number of configured boxen, Loop through all looking for what we want
    count = int(getRedisCount()) + 1

    # draw producers
    for key in range(1, count):
        serverData = getRedis(key)
        if serverData != None:
           if serverData['type'].lower() == 'producer':
              if serverData['location'].lower() == 'crozet':
                 datablock = json.dumps(serverData)
                 data = data + drawProducer(datablock, x, y)
                 y = y + len(serverData['ports'])*32 + SPACE   # draw space between boxes

    x = 1308
    y = 10

    # draw consumers
    for key in range(1, count):
        serverData = getRedis(key)
        if serverData != None:
           if serverData['type'].lower() == 'consumer':
              if serverData['location'].lower() == 'crozet':
                 datablock = json.dumps(serverData)
                 data = data + drawConsumer(datablock, x, y)
                 y = y + len(serverData['ports'])*32 + SPACE   # draw space between boxes

#    draw paths here
#    data = data + drawpath(x, y+236, x+100, x+320, y-72, 'blue', 1, 'name', 0, 'anims')

    data = data + '</svg>'
    return data


