from flask import Flask, request, render_template
import asset_actions
import json
import os
import sniff
import multiprocessing
from utilities.list_interfaces import get_interfaces


app = Flask(__name__, template_folder='template')


status="Offline"
@app.route('/')
# ‘/’ URL is bound with hello_world() function.
def hello_world():
    global status
    headings = ["name", "last_activity", "type", "protocols", "mac_addr", "vendor", "firmware_version", "model", "os",
                "plant"]
    try:
        data = json.loads(asset_actions.transmit_all_assets())
    except:
        data = {}
    return render_template("index.html", headings=headings, data=data, interfaces=get_interfaces(),status=status)


process=None
@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():
    # headings = ["name", "last_activity", "type", "protocols", "mac_addr", "vendor", "firmware_version", "model", "os",
    #             "plant"]
    # try:
    #     data = json.loads(asset_actions.transmit_all_assets())
    # except:
    #     data = {}
    # return render_template("index.html", headings=headings, data=data, interfaces=get_interfaces())
    return hello_world()

@app.route('/delete_devices',methods = ['POST', 'GET'])
def delete():
    asset_actions.delete_all_assets()
    return hello_world()

# main driver function
if __name__ == '__main__':
    app.run(debug=True, port=8080)
