from flask import Flask, request, render_template
import json
import sniff
import multiprocessing
from utilities.list_interfaces import get_interfaces
import yaml
app = Flask(__name__, template_folder='template')


status="Offline"
transfer_status="not transmitting"
process=None
periodic_transfer=None

try:
    yamlfile=open("config.yaml")
    data = yaml.load(yamlfile, Loader=yaml.FullLoader)
    ui_host=data["configuration"]["ui_host"]
    ui_port=int(data["configuration"]["ui_port"])

except Exception as e:
    ui_host="127.0.0.1"
    ui_port=8080

@app.route('/')
def hello_world():
    global status
    global transfer_status
    headings = ["name", "last_activity", "type", "protocols", "mac_addr", "vendor", "firmware_version", "model", "os",
                "plant"]
    try:
        with open("assets.json") as json_file:
            data = json.load(json_file)
    except:
        data = {}
    return render_template("index.html", headings=headings, data=data, interfaces=get_interfaces(),status=status,transfer_status=transfer_status)



@app.route('/start_sniff',methods = ['POST', 'GET'])
def start_sniff():
    global process
    global status
    interface = request.form.get('interface')
    process = multiprocessing.Process(target=sniff.start_sniff, args=(interface,))
    if(process.is_alive()):
        process.kill()
        process.start()
    else:
        process.start()
    status = "listening on "+interface+""
    return hello_world()

@app.route('/stop_sniff',methods = ['POST', 'GET'])
def stop_sniff():
    global process
    global status
    if(process):
        if(process.is_alive()):
            process.kill()
            status="Offline"
    return hello_world()

@app.route('/refresh',methods = ['POST', 'GET'])
def refresh():
    return hello_world()



if __name__ == '__main__':
    app.run(debug=True,host=ui_host, port=ui_port)
