import logging
import os

import base_detector


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 

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())
