import ipaddress
import os
import subprocess
import logging

import findssh

import findssh.threadpool
import platforms

EMPTY_MAC = 12*"0"
INCOMPLETE_MAC = "(incomplete)"


def get_macaddr_from_arp(ip=None):
    macs = []
    try:
        if platforms.PLATFORM == 'linux' or platforms.PLATFORM == 'rpi':
            with open('/proc/net/arp') as f:
                for line in f.readlines():
                    line = line.strip()
                    if line and line[0].isdigit():
                        words = line.split()
                        if len(words) > 2 and not ip or words[0] == ip:
                            mac = words[3].replace(":", "").lower()
                            if mac != EMPTY_MAC:
                                macs.append((words[0], mac))
        elif platforms.PLATFORM == 'mswin':
            process = subprocess.run(['arp', '-a'], stdout=subprocess.PIPE, universal_newlines=True)
            for line in process.stdout.splitlines():
                line = line.strip()
                if line and line[0].isdigit():
                    words = line.split()
                    if len(words) > 1 and not ip or words[0] == ip:
                        mac = words[1].replace("-", "").lower()
                        if mac != EMPTY_MAC:
                            macs.append((words[0], mac))
        elif platforms.PLATFORM == 'mac':
            process = subprocess.run(['arp', '-a'], stdout=subprocess.PIPE, universal_newlines=True)
            for line in process.stdout.splitlines():
                line = line.strip()
                words = line.split()
                if len(words) > 3:
                    line_ip = words[1].strip('()')
                    mac = words[3].replace("-", "").lower()
                    if mac != EMPTY_MAC and mac != INCOMPLETE_MAC and (not ip or line_ip == ip):
                        macs.append((line_ip, mac))
    except Exception as e:
        logging.getLogger('get_macaddr_from_arp').exception(e)
    return macs

def scan(service='http', port=80, timeout=1):
    network = findssh.netfromaddress(findssh.getLANip())
    hosts = list(findssh.threadpool.get_hosts(network, port, service, timeout))
    return hosts

if __name__ == "__main__":
    import pprint

    logging.basicConfig()
    hosts = scan()
    #print("Hosts with http:\n", pprint.pformat(hosts), "\n")
    print("Macs:\n", pprint.pformat(get_macaddr_from_arp()))
