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

ashburn_api = Blueprint('ashburn_api', __name__)

@ashburn_api.route('/ashburn/', methods=['GET','POST'])
def ashburn():
    block = 'none'
    return render_template('ashburn.html', block=block)

@ashburn_api.route('/refreshashburn/', methods=['GET','POST'])
def refreshashburn():
    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, 'Ashburn')

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

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

    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() == 'ashburn':
                 datablock = json.dumps(serverData)
                 data = data + drawProducer(datablock, x, y)
                 y = y + len(serverData['ports'])*32 + SPACE   # draw space between boxes

    # reposition to draw consumers, start from the top for consumers
    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() == 'ashburn':
                 datablock = json.dumps(serverData)
                 data = data + drawConsumer(datablock, x, y)
                 y = y + len(serverData['ports'])*32 + SPACE   # draw space between boxes

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



