#! /usr/bin/env python
# coding: utf-8
import requests
import json
from pprint import pprint



class zabbixApi(object):
    def __init__(self):
        self.url = 'http://127.0.0.1:9091/zabbix/api_jsonrpc.php'
        self.headers = {'Content-Type': 'application/json'}
        auth = {
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {
                "user": "user",
                "password":"EPy++z@BUT3X"
            },
            "id": 1,
            "auth":None,
        }
        response = requests.post(self.url, data=json.dumps(auth), headers=self.headers)
        self.authid = json.loads(response.text)['result']
        self.colors = ["1A7C11", "F63100", "2774A4", "A54F10", "FC6EA3", "6C59DC", "AC8C14", "611F27", "F230E0", "5CCD18", "BB2A02", "5A2B57", "89ABF8", "274482", "2B5429", "2774A4", "AC8C14", "611F27", "F230E0", "5CCD18", "BB2A02", "5A2B57", "89ABF8", "274482", "8048B4", "2B5429", "FD5434", "790E1F", "87AC4D", "000088", "000088"] 
    def from_itemid_to_value(self, itemid):
        sql = "select value_avg from trends_uint where itemid=%s  order by clock desc limit 1" % itemid

    def get_hosts(self):
        neirong={
            "jsonrpc": "2.0",
            "method": "host.get",
            "params": {
                "output": [
                    "hostid",
                    "host"
                ],
                "selectInterfaces": [
                    "interfaceid",
                    "ip"
                ]
            },
            "id": 2,
            "auth": self.authid
        }
        response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
        host_ids = []
        for host in response.json()['result']:
            host_ids.append(host['hostid'])
        return host_ids

#	java.pid.thread


    def get_jvmthread_host_item(self):
        host_ids = self.get_hosts()
        filter_result ={}
        d = {}
        for hostid in host_ids:
            neirong={
                "jsonrpc": "2.0",
                "method": "item.get",
                "params": {
                    "output": "extend",
                    "hostids": hostid,
                    "sortfield": "name"
                },
                "auth": self.authid,
                "id": 1
            }
            response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
            result = response.json()['result']
            l = []
            for item in result:
                if "Java pid  " in item['name']:
                    l.append(item['itemid'])
            if l :
                d[hostid] = l    
        return d

    def get_graph_by_name(self,hostid):
        neirong={
                "jsonrpc": "2.0",
                "method": "graph.get",
                "params": {
                    "output": "extend",
                    "hostids": hostid,
                    "sortfield": "name"
                },
                "auth": self.authid,
                "id": 1
            }
        response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
        result = response.json()['result'] 
        for item in result:
            if item['name'] == "jvm threads":
                 return item["graphid"]
        return

# action graph.update / graph.create

    def graph_define(self, action, hostid, itemids, *graphid):
        gitems = []
        for tup in zip(itemids, self.colors):
            gitems.append({"itemid":tup[0], "color": tup[1]})
        neirong={
                "jsonrpc": "2.0",
                "method": action,
                "params": {
                    "name": "jvm threads",
                    "width": 900,
                    "height":200,
                    "hostids": hostid,
                    "gitems": gitems
                },
                "auth": self.authid,
                "id": 1
            }
        if graphid:
            graphid = graphid[0]
            neirong["params"]["graphid"] = graphid
        response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
        result = response.json()
        print result
    
    def run(self):
        host_item = self.get_jvmthread_host_item()
        for host,items in host_item.items():
            graphid = self.get_graph_by_name(host)
            if not graphid:
                self.graph_define("graph.create" ,host, items)
            else:
                self.graph_define("graph.update", host, items, graphid)
         
        
if __name__ == "__main__":        
    zabbixApi().run()

