#!python
from __future__ import print_function

"""
sls_dig - client to fetch host information from sLS
"""
__author__ = 'sowmya'

from sls_client.records import *
from sls_client.query import *
import sls_client.find_host_info
from optparse import OptionParser
import sys

HOST_HW_PROCESSORCOUNT = 'host-hardware-processorcount'
HOST_HW_PROCESSORCORE = 'host-hardware-processorcore'
HOST_HW_PROCESSORSPEED = 'host-hardware-processorspeed'
HOST_HW_MEMORY = 'host-hardware-memory'

HOST_NET_TCP_AUTOTUNEMAXBUFFER_RECV='host-net-tcp-autotunemaxbuffer-recv'
HOST_NET_TCP_AUTOTUNEMAXBUFFER_SEND='host-net-tcp-autotunemaxbuffer-send'
HOST_NET_TCP_MAXBUFFER_RECV='host-net-tcp-maxbuffer-recv'
HOST_NET_TCP_MAXBUFFER_SEND='host-net-tcp-maxbuffer-send'
HOST_NET_TCP_CONGESTIONALGORITHM='host-net-tcp-congestionalgorithm'

HOST_OS_VERSION = 'host-os-version'
HOST_OS_NAME = 'host-os-name'
HOST_OS_KERNEL = 'host-os-kernel'

HOST_INTERFACE='host-net-interfaces'

HOST_ADMINISTRATORS='host-administrators'

LOCATION_CITY='location-city'
LOCATION_STATE='location-state'
LOCATION_COUNTRY='location-country'
LOCATION_SITE='location-sitename'
LOCATION_LATITUDE='location-latitude'
LOCATION_LONGITUDE='location-longitude'

PERSON_NAME='person-name'
PERSON_EMAILS='person-emails'

INTERFACE_ADDRESS = 'interface-addresses'
INTERFACE_NAME='interface-name'
INTERFACE_CAPACITY='interface-capacity'
INTERFACE_MTU='interface-mtu'
INTERFACE_MAC='interface-mac'

#TODO: Add location information, admin
def main():

    parser = OptionParser()

    parser.add_option("-o", "--output",
                      dest="output_type",
                      help="output type - json or console",
                      choices=["console","json","list"],
                      default="console"

    )
    (options, args) = parser.parse_args()
    if (len(args)!= 1):
        print("Please specify hostname")
        sys.exit(1)

    hostname=args[0]
    if(options.output_type=="json"):
        print(sls_client.find_host_info.get_host_info_json(hostname))

    elif(options.output_type=="console"):
        result = sls_client.find_host_info.get_host_info(hostname)
        for host in result:
            interfaces=host[HOST_INTERFACE]
            core=1
            count=1
            print("\n***** HOST HARDWARE *****", end='')
            print("\nMemory:", end='')
            for memory in host[HOST_HW_MEMORY]:
                print(memory, end='')
            if(host[HOST_HW_PROCESSORCORE]):
                core = int(host[HOST_HW_PROCESSORCORE][0])
            if(host[HOST_HW_PROCESSORCOUNT]):
                count = int(host[HOST_HW_PROCESSORCOUNT][0])

            print("\nNumber of processors: {}".format(count))

            for i in range(0,count):
                print("\nProcessor #"+str(i)+": ", end='')
                cpp=core
                if (count>1):
                    cpp = int(core/count)
                print(str(cpp)+" cores", end='')
                print("\nProcessor #"+str(i)+" Speed: ", end='')
                for speed in host[HOST_HW_PROCESSORSPEED]:
                    print(speed, end='')

            print("\n\n***** HOST OS *****", end='')
            print("\nOS: ", end='')
            for osname in host[HOST_OS_NAME]:
                print(osname, end='')

            print("\nOS Version: ", end='')
            for osversion in host[HOST_OS_VERSION]:
                print(osversion, end='')

            print("\nOS Kernel: ", end='')
            for oskernel in host[HOST_OS_KERNEL]:
                print(oskernel)

            print("\n***** HOST NETWORKING *****\n", end='')
            if (interfaces):
                i=0
                for interface in interfaces:
                    print("\n*** INTERFACE "+str(i)+" ***" , end='')
                    i+=1
                    print("\n"+ INTERFACE_NAME+":", end='')
                    for ifname in interface[INTERFACE_NAME]:
                        print(ifname, end='')

                    print("\n"+ INTERFACE_ADDRESS+":", end='')
                    for ip in interface[INTERFACE_ADDRESS]:
                        print(ip, end='')

                    print("\n"+ INTERFACE_MAC+":", end='')
                    for mac in interface[INTERFACE_MAC]:
                        print(mac, end='')

                    print("\n"+ INTERFACE_CAPACITY+":", end='')
                    for cap in interface[INTERFACE_CAPACITY]:
                        int_cap = int(cap)
                        c = _format_metrics(int_cap)
                        print(c+"bps", end='')

                    print("\n"+ INTERFACE_MTU+":", end='')
                    for mtu in interface[INTERFACE_MTU]:
                        print(mtu)

            print("\n***** HOST TCP PARAMETERS *****", end='')
            print("\nCongestion Algorithm: ", end='')
            for alg in host[HOST_NET_TCP_CONGESTIONALGORITHM]:
                print(alg, end='')
            print("\nRECV Autotunemaxbuffer", end='')
            for buf in host[HOST_NET_TCP_AUTOTUNEMAXBUFFER_RECV]:
                print(buf, end='')
                print("\nRECV Maxbuffer: ", end='')
            for buf in host[HOST_NET_TCP_MAXBUFFER_RECV]:
                print(buf, end='')
            print("\nSEND Autotunemaxbuffer: ", end='')
            for buf in host[HOST_NET_TCP_AUTOTUNEMAXBUFFER_SEND]:
                print(buf, end='')
            print("\nSEND Maxbuffer: ", end='')
            for buf in host[HOST_NET_TCP_MAXBUFFER_SEND]:
                print(buf)


            print("\n***** HOST LOCATION *****", end='')

            if( LOCATION_SITE in host and host[LOCATION_SITE]):
                print("\nSite Name: ", end='')
                for site in host[LOCATION_SITE]:
                    print(site, end='')

            if(LOCATION_CITY in host and host[LOCATION_CITY]):
                print("\nCity: ", end='')
                for city in host[LOCATION_CITY]:
                    print(city, end='')

            if(LOCATION_STATE in host and host[LOCATION_STATE]):
                print("\nState: ", end='')
                for state in host[LOCATION_STATE]:
                    print(state, end='')

            if(LOCATION_COUNTRY in host and host[LOCATION_COUNTRY]):
                print("\nCountry: ", end='')
                for country in host[LOCATION_COUNTRY]:
                    print(country, end='')

            if(LOCATION_LATITUDE in host and host[LOCATION_LATITUDE]):
                print("\nLatitude: ", end='')
                for lat in host[LOCATION_LATITUDE]:
                    latitude = float(lat)
                    print('%.2f' % latitude, end='')

            if(LOCATION_LONGITUDE in host and host[LOCATION_LONGITUDE]):
                print("\nLongitude: ", end='')
                for lo in host[LOCATION_LONGITUDE]:
                    longitude = float(lo)
                    print ('%.2f' %longitude)

            print("\n***** HOST ADMIN *****", end='')
            admins=host[HOST_ADMINISTRATORS]
            for admin in admins:
                print("\nAdmin Name: ", end='')
                for name in admin[PERSON_NAME]:
                    print(name, end='')

                print("\nAdmin Email: ", end='')
                for email in admin[PERSON_EMAILS]:
                    print(email, end='')

                print("\nCity :", end='')
                for city in admin[LOCATION_CITY]:
                    print(city, end='')

                print("\n State: ", end='')
                for state in admin[LOCATION_STATE]:
                    print(state, end='')

                print("\nCountry: ", end='')
                for country in admin[LOCATION_COUNTRY]:
                    print(country)



    else:
        print(sls_client.find_host_info.get_host_info(hostname))


def _format_metrics(capacity):
    lower_limit=1
    upper_limit=1000
    if(capacity):
        if (capacity/1000000000 >= lower_limit and capacity/1000000000 < upper_limit):
            cap = capacity/1000000000
            return str(cap)+" G"
        elif (capacity/1000000 >= lower_limit and capacity/1000000 < upper_limit):
            cap = capacity/1000000
            return str(cap)+" M"
        elif (capacity/1000 >=lower_limit and capacity/1000 <upper_limit):
            cap = capacity/1000
            return str(cap)+" K"
        else:
            return str(capacity)


def __parse_float_from_string(string):
    if(string):
        result=[float(x) for x in string.split() if x.isdigit()]



if __name__=='__main__':
    main()
