from flask import Blueprint, render_template, request, jsonify, redirect, url_for
from mydatabase import *
from packetbroker import *
import random
import redis
import MySQLdb
import base64
import time
import json
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

pathconfig_api = Blueprint('pathconfig_api', __name__)

STARTSERVER = ""
SAVEPORT = 0
SOURCEPORT = 0

@pathconfig_api.route('/startstop/', methods=['POST','GET'])
def startstop():
    id = request.form['id']
    serverid = id.split("*")
    sname = serverid[0]
    id = serverid[2]

    db = MySQLdb.connect(host="localhost", passwd="veronicaHammerhead27!", db="veronica")
    cr = db.cursor()
    sql = "SELECT * FROM servers where name='%s';" % sname
    cr.execute(sql)
    result = cr.fetchall()
    ps = result[0][16]
    playstop = json.loads(base64.b64decode(ps))
    if playstop[int(id)] == 'stop':
       playstop[int(id)] = 'play'
    else:
       playstop[int(id)] = 'stop'
    ps = base64.b64encode(json.dumps(playstop))
    sql = "UPDATE servers SET playstat='%s' where name='%s';" % (ps, sname)
    cr.execute(sql)
    db.commit()

    initializeDatabase()

    return " "


@pathconfig_api.route('/deletepath/', methods=['POST','GET'])
def deletepath():
    id = request.form['id']

    serverid = id.split("*")
    sname = serverid[0]
    port = serverid[1]
    id   = int(serverid[2])

    db = MySQLdb.connect(host="localhost", passwd="veronicaHammerhead27!", db="veronica")
    cr = db.cursor()
    sql = "SELECT * FROM servers where name='%s';" % sname
    cr.execute(sql)
    result = cr.fetchall()
    sp = result[0][11]
    location = result[0][7]

    pathstart = json.loads(base64.b64decode(sp))
    path = pathstart[port]
    del path[id]
    pathstart[port] = path
    ps = base64.b64encode(json.dumps(pathstart))

    sp = result[0][12]
    pathend = json.loads(base64.b64decode(sp))
    path = pathend[port]

    # get filter ID and delete from packet broker
    did = path[id][3]
    deletefilter(did)

    del path[id]
    pathend[port] = path
    pe = base64.b64encode(json.dumps(pathend))

    sql = "UPDATE servers SET pathstart='%s', pathend='%s' where name='%s';" % (ps, pe, sname)
    cr.execute(sql)
    db.commit()

    initializeDatabase()

    return " "


@pathconfig_api.route('/startpath/', methods=['POST','GET'])
def startpath():
    global STARTSERVER
    global SAVEPORT
    global SOURCEPORT

    sname  = request.form['sname']
    port   = str(request.form['port'])    # relative port 
    x      = str(request.form['x'])
    y      = str(request.form['y'])

    if STARTSERVER != "":                 # check for path started, should be nothing
       STARTSERVER = ""                   # start over, clear path state
       return "-1"

    STARTSERVER = sname
    SAVEPORT = port

    db = MySQLdb.connect(host="localhost", passwd="veronicaHammerhead27!", db="veronica")
    cr = db.cursor()
    sql = "SELECT * FROM servers where name='%s';" % sname
    cr.execute(sql)
    result = cr.fetchall()
    location = result[0][7]

    pp = result[0][10]       # switch port
    switchports = json.loads(base64.b64decode(pp))
    SOURCEPORT = switchports[int(port)]

    if not SOURCEPORT.isdigit():
       print "SOURCEPORT", SOURCEPORT
       STARTSERVER = ""
       SAVEPORT = 0
       return "-3"

    sp = result[0][11]
    pathstart = json.loads(base64.b64decode(sp))
    r0 = random.randrange(820,1100,16)

    try:
       path = pathstart[port]
    except:
       path = []

    path.append([x,y,r0])
    pathstart[port] = path
    ps = base64.b64encode(json.dumps(pathstart))

    sql = "UPDATE servers SET pathstart='%s' where name='%s';" % (ps, STARTSERVER)
    cr.execute(sql)
    db.commit()

    initializeDatabase()

    return "0"     # return success


@pathconfig_api.route('/endpath/', methods=['POST','GET'])
def endpath():
    global STARTSERVER
    global SAVEPORT
    global SOURCEPORT

    sname = request.form['sname']
    cport  = request.form['port']
    x  	   = request.form['x']
    y  	   = request.form['y']

    if STARTSERVER == "":             # should have something in here!
       return "-2"

    port = SAVEPORT

    db = MySQLdb.connect(host="localhost", passwd="veronicaHammerhead27!", db="veronica")
    cr = db.cursor()
    sql = "SELECT * FROM servers where name='%s';" % STARTSERVER
    cr.execute(sql)
    result = cr.fetchall()
    location = result[0][7]

    # get the translation from physical to packetbroker IDs
    r = redis.Redis(host='127.0.0.1', port='6379')
    pp = r.get("packetPorts")
    packetports = pp.split()

    endport = packetports[int(cport)-1]
    startport = packetports[int(SOURCEPORT)]

    # packet broker source port
    print "FILTER PARMS", startport, endport
    id = createfilter([startport], [endport])
    print "FILTER ID", id

    sp = result[0][12]
    pathend = json.loads(base64.b64decode(sp))
    r0 = random.randrange(820,1100,16)

    try:
       path = pathend[port]
    except:
       path = []

    path.append([x,y,r0,id])
    pathend[port] = path
    ps = base64.b64encode(json.dumps(pathend))

    sql	= "UPDATE servers SET pathend='%s' where name='%s';" % (ps, STARTSERVER)
    cr.execute(sql)
    db.commit()

    initializeDatabase()

    STARTSERVER = ""
    STARTPORT = 0

    return "0"
