from flask import Flask, request, render_template
import json
import sniff
import multiprocessing
from utilities.list_interfaces import get_interfaces
import asset_actions
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:
        data = json.loads(asset_actions.transmit_all_assets())
    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()

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

@app.route('/start_transfer',methods = ['POST', 'GET'])
def transfer_data():
    global transfer_status
    global periodic_transfer
    transfer_status="transmitting"
    periodic_transfer = multiprocessing.Process(target=asset_actions.periodic_transmit_all_assets, args=())
    if(periodic_transfer.is_alive()):
        periodic_transfer.kill()
        periodic_transfer.start()
    else:
        periodic_transfer.start()
    return hello_world()

@app.route('/stop_transfer',methods = ['POST', 'GET'])
def stop_transfer_data():
    global transfer_status
    global periodic_transfer
    if (periodic_transfer):
        if (periodic_transfer.is_alive()):
            periodic_transfer.kill()
            transfer_status = "not transmitting"
        else:
            transfer_status = "not transmitting"
    else:
        transfer_status = "not transmitting"
    return hello_world()

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