import os
from threading import Thread
from scapy.layers.dot11 import Dot11
from scapy.sendrecv import sniff


class Sniffer(Thread):
    def __init__(self, interface="wlan0"):
        super().__init__()
        self.packet_delay = 0
        self.last_packet = None
        self.interface = interface
        self.stopped = False

    def run(self):
        self.stopped = False
        sniff(iface=self.interface, prn=self.callBack, stop_filter=self.stopfilter)

    def stopfilter(self, x):
        print(self.stopped)
        return not self.stopped

    def init(self):
        os.system(f"airmon-ng check kill && airmon-ng start {self.interface}")

    def setChannel(self, channel: int):
        os.system(f"iw dev wlan0 set channel {channel}")
        print(f"Changing channel to {channel}")

    def stop(self):
        self.stopped = True

    def callBack(self, pkg):
        if pkg.haslayer(Dot11):
            if pkg.type == 0 and pkg.subtype == 8:
                if self.last_packet is not None:
                    self.packet_delay = pkg.time - self.last_packet.time
                self.last_packet = pkg