#!/usr/bin/env python
import http.client, mimetypes, json

realm = "prod.addigy.com"
clientID = "Your_Client_ID"
clientSecret = "Your_Client_Secret"


class Node:
	def __init__(self, nodeId, nodeName, tabCount):
		self.nodeId = nodeId
		self.children = []
		self.nodeName = nodeName
		self.tabCount = tabCount

class Device:
  def __init__(self, DeviceName, policy_id):
    self.DeviceName = DeviceName
    self.policy_id = policy_id

class Policy:
  def __init__(self, name, policy_id, parent):
    self.name = name
    self.policy_id = policy_id
    self.parent = parent

def set_tabCount(tabCount, childrenList):
	for child in childrenList[:]:
		child.tabCount = tabCount

def add_all_children(root, childrenList):
	queue = []
	for policy in childrenList[:]:
		if policy.parent == root.nodeId:
			queue.append(Node(policy.policy_id,policy.name,0))
	if len(queue) == 0:
		return root
	else:
		for node in queue[:]:
			node = add_all_children(node,childrenList)
			root.children.append(node)
			queue.remove(node)
	return root


deviceList = []
policyList = []
treeList = []

conn = http.client.HTTPSConnection(realm)
payload = ''
headers = {}
conn.request("GET", "/api/devices?client_id=%s&client_secret=%s" % (clientID,clientSecret), payload, headers)
res = conn.getresponse()
data = res.read()
dataString = data.decode("utf-8")
jsonObject = json.loads(dataString)
jsonSize = len(jsonObject)
totalDeviceCount = jsonSize

conn = http.client.HTTPSConnection(realm)
payload = ''
headers = {}
conn.request("GET", "/api/policies?client_id=%s&client_secret=%s" % (clientID,clientSecret), payload, headers)
res = conn.getresponse()
data = res.read()
dataString = data.decode("utf-8")
jsonPolicyObject = json.loads(dataString)


for i in range(jsonSize):
	deviceList.append(Device(jsonObject[i]['Device Name'],jsonObject[i]['policy_id']))

for i in range(len(jsonPolicyObject)):
	policyList.append(Policy(jsonPolicyObject[i]['name'],jsonPolicyObject[i]['policyId'],jsonPolicyObject[i]['parent']))

policyNameDict = {'key': 'value'}
policyDict = {'key': '1'}

for device in deviceList:
	if not device.policy_id in policyDict:
		policyDict[device.policy_id] = 1
	else:
		policyDict[device.policy_id] = policyDict[device.policy_id]+1

policyDeviceCount = 0
for policy in policyList[:]:
	if policy.parent == None:
		conn = http.client.HTTPSConnection(realm)
		payload = ''
		headers = {}
		conn.request("GET", "/api/policies/devices?policy_id=%s&client_id=%s&client_secret=%s" % (policy.policy_id,clientID,clientSecret), payload, headers)
		res = conn.getresponse()
		data = res.read()
		dataString = data.decode("utf-8")
		jsonObject = json.loads(dataString)
		jsonSize = len(jsonObject)

		policyDeviceCount = policyDeviceCount + jsonSize
		treeList.append(Node(policy.policy_id,policy.name,0))
		policyList.remove(policy)
		

for tree in treeList[:]:
	test = add_all_children(tree,policyList)


policyListIndex = 0
tabAmount = 0
for tree in treeList[:]:
			tabAmount = 0
			queue = []
			queue.append(tree)
			depth = 0
			while queue[:]:
				for node in queue[:]:
					currentNode = queue.pop()
					conn = http.client.HTTPSConnection(realm)
					payload = ''
					headers = {}
					conn.request("GET", "/api/policies/devices?policy_id=%s&client_id=%s&client_secret=%s" % (currentNode.nodeId,clientID,clientSecret), payload, headers)
					res = conn.getresponse()
					data = res.read()
					dataString = data.decode("utf-8")
					jsonObject = json.loads(dataString)
					jsonSize = len(jsonObject)
					print('\t' * currentNode.tabCount + "Policy Name: " + currentNode.nodeName)
					print('\t' * currentNode.tabCount + "Devices: " + str(jsonSize))
					print("\n")

					if len(currentNode.children) > 0:
						tabAmount = tabAmount + 1
					for child in currentNode.children[:]:
						child.tabCount = tabAmount
						queue.append(child)
					depth = depth+1
print("No Policy")
print(str((totalDeviceCount-policyDeviceCount))+ " Devices\n")						
print("Total Devices: "+ str(totalDeviceCount))