#!/usr/bin/python3
from xmlrpc.client import ServerProxy
import sys
import http.client

IP = sys.argv[1]
proxy = ServerProxy('http://%s/xmlrpc' % IP)


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


def index():
    if GetStatusCode(str(IP), "/languages") == 200:
        Rectifiers = proxy.db.get(['Number-Of-Registered-Rectifiers'])[0]
        print(('Batteries'))
        for num in range(1, Rectifiers):
            print(('Rectifier-{0}'.format(num)))


def num_indexes():
    if GetStatusCode(str(IP), "/languages") == 200:
        Rectifiers = proxy.db.get(['Number-Of-Registered-Rectifiers'])[0]
        Rectifiers += 1
        print((Rectifiers))


def get(index):
    if GetStatusCode(str(IP), "/languages") == 200:
        if index == 'Batteries':
            query = 'Battery-Temperature'
            print((proxy.db.get([query])[0]))
        elif index[:10] == 'Rectifier-':
            query = 'Rectifier-Heatsink-Temperature:{0}-{0}'.format(index[10:])
            print((proxy.db.get([query])[0][0]))
        else:
            return



def query():
    if GetStatusCode(str(IP), "/languages") == 200:
        Rectifiers = proxy.db.get(['Number-Of-Registered-Rectifiers'])[0]
        Values = proxy.db.get([
            'Battery-Temperature',
            'Rectifier-Heatsink-Temperature:1-%s' % Rectifiers
        ])

        if len(Values) > 0:
            outString = ""
            outString += ("Batteries:%s" % Values[0])
            numRect = 1
            for Rectifier in Values[1]:
                if type(Rectifier) is float:
                    outString += (" Rectifier-{0}:{1}".format(numRect,
                    Rectifier))
                elif type(Rectifier) is dict:
                    outString += (" Rectifier-{0}:{1}".format(numRect,
                    Values[1][Rectifier['repeatLast']]))
                numRect += 1
            print(outString)

if len(sys.argv) > 2:
    if sys.argv[2] == 'index':
        index()
    elif sys.argv[2] == 'num_indexes':
        num_indexes()
    elif sys.argv[2] == 'get' and len(sys.argv) == 4:
        get(sys.argv[3])
    elif sys.argv[2] == 'query':
        query()

sys.exit(0)

