import logging
import os
import subprocess

import base_detector
import rights


class DNSMasqDetector(base_detector.BaseDetector):

    VID_PID = {'VID': 'DSMQ', 'PID':'DSMQ'}

    LEASES_FILE = '/var/lib/misc/dnsmasq.leases'
    """
    expire epoch, macaddr, ip, hostname or just *, client-id (unreliable type):macaddr
    01 is type code for ethernet, but shown for wifi connections
    0 82:86:07:c2:1a:4e 192.168.61.49 * 01:82:86:07:c2:1a:4e
    0 d2:42:9c:d1:43:2c 192.168.61.90 * 01:d2:42:9c:d1:43:2c
    """

    # ARP_FILE = '/proc/net/arp'
    # IP address       HW type     Flags       HW address            Mask     Device
    # 192.168.61.49    0x1         0x0         82:86:07:c2:1a:4e     *        wlan0_ap
    # 192.168.61.90    0x1         0x2         d2:42:9c:d1:43:2c     *        wlan0_ap

    def get_printers_list(self):
        printers = []
        if os.path.exists(self.LEASES_FILE):
            try:
                with open(self.LEASES_FILE) as f:
                    for line in f.readlines():
                        words = line.split()
                        if len(words) > 2:
                            printer = {}
                            printer.update(self.VID_PID)
                            printer['SNR'] = words[1].replace(":", "")
                            printer['IP'] = words[2]
                            printers.append(printer)
            except Exception as e:
                logging.getLogger('__name__').exception('Error reading dnsmasq leases: ' + str(e))
        return printers 

    def forget_printer(self, ip_to_remove):
        self.logger.info(f'Removing IP {ip_to_remove} from leases file')
        if os.path.exists(self.LEASES_FILE):
            try:
                with open(self.LEASES_FILE, "r+") as f:
                    new_content = ''
                    for line in f.readlines():
                        if ip_to_remove not in line.split():
                            new_content += line
                    f.seek(0)
                    f.truncate(0)
                    f.write(new_content)
                    return True
            except Exception as e:
                self.logger.exception('Error reading dnsmasq leases: ' + str(e))
            finally:
                try:
                    subprocess.call(["sudo", "systemctl", "start", 'dnsmasq'])
                except:
                    pass
        return False

if __name__ == "__main__":
    import pprint
    logging.basicConfig(level=logging.INFO)
    # logging.basicConfig(level=logging.DEBUG)
    d = DNSMasqDetector()
    print("DNSMasq leases: ")
    pprint.pprint(d.get_printers_list())
