#!/usr/bin/python3
#from netaddr import IPNetwork
#from netaddr import IPAddress
from xmlrpc.client import ServerProxy
#import sqlite3
import socket
import csv
import queue
import threading
import sys
import http.client

WORKERS = 10

inFilePath = sys.argv[1]


def GetStatusCode(host, path="/"):
    try:
        conn = http.client.HTTPConnection(host)
        conn.request("GET", path)
        return conn.getresponse().status
    except Exception:
        return None


class Worker(threading.Thread):

    def __init__(self, Settings, Results):
        self.__Settings = Settings
        self.__Results = Results
        self.parent = threading.current_thread()
        threading.Thread.__init__(self)

    def run(self):
        retry = False
        socket.setdefaulttimeout(5)
        while 1:
            DevSettings = self.__Settings.get()
            if DevSettings is None:
                self.__Results.put(None)
                break

            IP = DevSettings.pop('IP', None)

            for k in list(DevSettings.keys()):
                if k.startswith('Alarm-Name'):
                    DevSettings.pop(k)

            if GetStatusCode(str(IP), "/languages") == 200:
                #print((self.getName() + ' processing: ' + str(IP)))
                while True:
                    proxy = ServerProxy('http://%s/xmlrpc' % IP)
                    try:
                        #print(((DevSettings)))
                        Result = proxy.db.set(DevSettings)
                    except socket.timeout:
                        retry = True
                        continue

                    if retry:
                        retry = False
                    else:
                        break

                if len(Result) > 0:
                    Result['IP'] = str(IP)
                    self.__Results.put(Result)
            else:
                print((self.getName() + ' skipping: ' + str(IP)))


def Input():
    with open(inFilePath, 'r', newline='') as inFile:
        csvReader = csv.DictReader(inFile)

        for row in csvReader:
            Settings.put(row)
        inFile.close()

    for i in range(WORKERS):
        Settings.put(None)


def Output():
    Count = WORKERS
    while 1:
        Row = Results.get()
        if Row is None:
            if Count > 1:
                Count -= 1
            else:
                break
        else:
            print(((Row['IP'] + ':' + Row['resultString'])))

Settings = queue.Queue(0)
Results = queue.Queue(0)

Input()

for i in range(WORKERS):
    Worker(Settings, Results).start()

if threading.current_thread() is not threading.main_thread():
    sys.exit(0)

Output()

sys.exit(0)

