import json
import sniff
import multiprocessing


from security_management.settings import CREDENTIALS
from utilities.list_interfaces import get_interfaces
from datetime import datetime, timedelta
from django.http import HttpResponse
from django.template import loader
from django.shortcuts import redirect


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


def check_session(request):
    if 'user' in request.session:
        return True
    else:
        return False


def login(request):
    template = loader.get_template('login.html')
    return HttpResponse(template.render({}, request))


def sign_out(request):
    if 'user' in request.session:
        request.session.flush()
    return redirect('login')


def validate_user(request):
    user_name = request.POST['username']
    password = request.POST['password']
    if user_name == CREDENTIALS.get("username") and password == CREDENTIALS.get("password"):
        request.session['user'] = user_name
        return redirect('index')
    else:
        return HttpResponse("<script>alert('Invalid Login Credentials!'); window.history.back();</script>")


def check_status(timestamp):
    current_time = datetime.now()
    given_time = datetime.strptime(timestamp, "%d-%m-%y %H:%M:%S")
    time_difference = current_time - given_time
    five_minutes = timedelta(minutes=5)
    status = "Active"
    if time_difference > five_minutes:
        status = "Inactive"
    return status


def security_management_offline(request):
    if check_session(request):
        global status
        global transfer_status
        headings = [
            "Name", "Last Activity", "Type", "Protocols", "MAC Address",
            "Vendor", "Firmware Version", "Model"
        ]
        try:
            with open("assets.json") as json_file:
                data = json.load(json_file)
        except:
            data = {}
        data_list = []
        count = 0
        for data_item in data:
            count += 1
            data_list.append(
                [
                    count,
                    data_item,
                    data[data_item]["last_activity"],
                    data[data_item]["dev_type"],
                    data[data_item]["protocols"],
                    data[data_item]["mac"],
                    data[data_item]["vendor"],
                    data[data_item]["firmware"],
                    data[data_item]["model"],
                    check_status(data[data_item]["last_activity"])
                ]
            )
        template = loader.get_template('index.html')
        user_name = request.session['user']
        context = {
            'interface_list': [interface for interface in get_interfaces() if interface != ""],
            'data': data_list,
            'heading': headings,
            'status': status,
            'user_details': user_name.title()
        }
        return HttpResponse(template.render(context, request))
    else:
        return redirect('login')
    

def start_sniff(request):
    interface = request.POST['interface']
    global process
    global status
    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 security_management_offline(request)


def stop_sniff(request):
    global process
    global status
    if process:
        if process.is_alive():
            process.kill()
            status = "Offline"
    return security_management_offline(request)


def refresh(request):
    return redirect('index')
