import subprocess
import json
import time

import base
import rest
from config import cfg


nsaddr = "http://%s:%d" % (cfg.get("host","ip"), cfg.getint("host","nsport"))
GetWIFIIPURL = base.joinURL(nsaddr, "node/getwifiip")
SetWIFIIPURL = base.joinURL(nsaddr, "node/setip")

DefaultWIFIIP = cfg.get("autoset","ip")
DefaultWIFIMask = cfg.get("autoset","mask")
DefaultWIFIGateway = cfg.get("autoset","gateway")

ReachableRetryCount = 4
ReachableRetryInterval = 0.5     #s


class _wifinetwork():
    def GetIPInfo(self, token):
        (hr, resp) = rest.get(GetWIFIIPURL, token)
        if hr:
            return json.loads(resp)
        else:
            return None
        
    def SetIPInfo(self, token, iface, wifiid, wifipw):
        param = json.dumps({
            "iface": iface, 
            "iswifi": True, 
            "wifiid": wifiid, 
            "wifipw": wifipw, 
            "ip": DefaultWIFIIP,  
            "mask": DefaultWIFIMask, 
            "gateway": DefaultWIFIGateway
        })
        (hr, resp) = rest.post(SetWIFIIPURL, param, token)
        return hr

    def IPReachable(self, ip):
        for i in range(ReachableRetryCount):
            result= subprocess.run(["ping", "-c", "1", ip], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            if result.returncode == 0 :
                return True
            
            time.sleep(ReachableRetryInterval)
            
        return False


WIFINetWork = _wifinetwork()
        