#!/usr/bin/env python3

import sqlite3
from sqlite3 import Error 
import tkinter as tk                    
from tkinter import ttk
from scapy.all import *
from datetime import datetime

def create_connection(db_file):
    conn = None
    try:
        conn = sqlite3.connect(db_file)
    except Error as e:
        print(e)
    return conn

def select_all_pcaprecords(conn):
    cur = conn.cursor()
    cur.execute("SELECT * FROM pcap_records")

    rows = cur.fetchall()
    return rows

def open_popup(text_display):
    top = tk.Toplevel(mainwindow)
    top.geometry("550x250")
    top.title("Analysis Results!")
    popup_text = tk.Text(top, height=10, width=65,font=('Consolas',10))
    popup_text.grid(row=0,column=0,padx=5,pady=5,sticky=tk.W)
    popup_text.insert(tk.END,text_display)

def callback(event):
    filepath = "./outputfiles/"
    # get the index of the mouse click
    index = event.widget.index("@%s,%s" % (event.x, event.y))

    # get the indices of all "adj" tags
    tag_indices = list(event.widget.tag_ranges('tag'))

    # iterate them pairwise (start and end index)
    for start, end in zip(tag_indices[0::2], tag_indices[1::2]):
        # check if the tag matches the mouse click index
        if event.widget.compare(start, '<=', index) and event.widget.compare(index, '<', end):
            # return string between tag start and end
            filename = filepath + event.widget.get(start, end)
            print(filename)
            file1 = open(filename,'r')
            lines = file1.readlines()
            d = ""
            for line in lines:
                d += line.strip() + "\n"

            open_popup(d)

def display_to_text(in_data):
    displaytext.tag_config("tag",foreground="blue")  
    displaytext.tag_bind("tag","<Button-1>", callback)
    displaytext.insert(tk.END, 'ID' + "\t" + "PCAP Filename" + "              " + "Date" + "\t\t\t\t" + "Time" + "\t" + "Output File\n")
    displaytext.insert(tk.END, '==' + "\t" + "==========================" + "\t" + "========" + "\t" + "====" + "\t" + "===========\n")
    for row in in_data:
        displaytext.insert(tk.END, str(row[0]) + "\t" + row[1] + "   \t\t\t" + row[2] + "\t" + row[3] + " " + row[4] + "\t")
        displaytext.insert(tk.END,row[4],"tag")
        displaytext.insert(tk.END,"\n")

def get_current_date():
    now = datetime.now()
    return now.strftime('%Y%m%d')

def get_current_time():
    now = datetime.now()
    return now.strftime('%H%M%S')


def analysispcap():
    pcapFile = getfiletextbox.get() 
    pcap = rdpcap(pcapFile)
    numofpackets = len(pcap)
    resultstextbox.insert(tk.END,numofpackets)

def saveresult():
    pcapFile = getfiletextbox.get()
    analysis_date = get_current_date()
    analysis_time = get_current_time()
    analysis_output = resultstextbox.get("1.0","end-1c")
    output_filename = analysis_date + analysis_time + '.txt'
    print(pcapFile)
    print(analysis_date)
    print(analysis_time)
    print(analysis_output)
    print(output_filename)
    
# ====================== Main Start Here =====================================================

database = r"saspdemo.db"
conn = create_connection(database)
rows = select_all_pcaprecords(conn)
data = []

for row in rows:
    data.append([row[0], row[1], row[2], row[3], row[4]])

mainwindow = tk.Tk()
mainwindow.title("SASP Part B Assignment AY2223 - PCAP Analysis By Chan Tai Man")
tabControl = ttk.Notebook(mainwindow)
  
tab1 = ttk.Frame(tabControl)
tab2 = ttk.Frame(tabControl)
  
tabControl.add(tab1, text ='Network Traffic Analysis')
tabControl.add(tab2, text ='History')
tabControl.pack(expand = 1, fill ="both")

# =================== tab 1 GUI Layout ========================================================
  
getfilelabel = tk.Label(tab1,text='Start to work on your assignment',fg='red',font=('Consolas',12))
getfilelabel.grid(row=0,column=0,padx=5,sticky=tk.W)


# =================== tab 2 GUI Layout ========================================================

displaybtn = tk.Button(tab2, text="DISPLAY", fg='blue', width=20, command=lambda:display_to_text(data))
displaybtn.grid(row=0,column=0, padx=5,pady=10,sticky=tk.W)

displaytext = tk.Text(tab2,height=10, width=100,font=('Consolas',10))
displaytext.grid(row=2,column=0,padx=5,pady=5,sticky=tk.W)

mainwindow.mainloop()  
