#! /usr/bin/env python
# coding: utf-8
import requests
import json
import pymysql
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":"password"
            },
            "id": 1,
            "auth":None,
        }
        response = requests.post(self.url, data=json.dumps(auth), headers=self.headers)
        self.authid = json.loads(response.text)['result']

        conn = pymysql.connect(
            host="127.0.0.1",
            user="zabbix",
            password="openet123",
            database="zabbix",
            charset="utf8")
        self.cursor = conn.cursor()
    
    def from_itemid_to_value(self, itemid):
        sql = "select value_avg from trends_uint where itemid=%s  order by clock desc limit 1" % itemid
        self.cursor.execute(sql)
        data =  self.cursor.fetchall()
        try:
            value = data[0][0]
        except:
            value = 0
        return value
   
    def from_graphid_to_itemid(self, graphid):
        sql = "select itemid  from graphs_items where graphid= %s" % graphid 
        self.cursor.execute(sql)
        ##### tobe continue
        data = self.cursor.fetchall()
        _in, _out = data
        _in = _in[0]
        _out = _out[0]
        _in_v = self.from_itemid_to_value(_in)
        _out_v = self.from_itemid_to_value(_out)
        if _in_v > _out_v :
            _out_v, _in_v  = _in_v, _out_v
        return _out_v
        
	

    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
    
    def get_conn_value(self):
        host_ids = self.get_hosts()
        filter_result ={}
        for hostid in host_ids:
            neirong={
                "jsonrpc": "2.0",
                "method": "item.get",
                "params": {
                    "output": "extend",
                    "hostids": hostid,
                    "search": {
                        "key_": "conn.all"
                    },
                    "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.get('name') == "conn.all":
               # filter_result[item.get("itemid")] = int(item.get("lastvalue"))
                filter_result[hostid] = int(item.get("lastvalue"))
        return sorted(filter_result.items(), key=lambda item:item[1], reverse=True)


    def get_cpu_value(self):
        host_ids = self.get_hosts()
        filter_result ={}
        for hostid in host_ids:
            neirong={
                "jsonrpc": "2.0",
                "method": "item.get",
                "params": {
                    "output": "extend",
                    "hostids": hostid,
                    "search": { 
                        "key_": "system.cpu.util[,user]"
                    },
                    "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.get('name') == "conn.all":
               # filter_result[item.get("itemid")] = int(item.get("lastvalue"))
                filter_result[hostid] = float(item.get("lastvalue"))
        return sorted(filter_result.items(), key=lambda item:item[1], reverse=True)



    def get_traffic_value(self):
        host_ids = self.get_hosts()
        filter_result ={}
        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']
            last_value = 0
            for item in result:
                if "network traffic on" in item['name']:
                    if int(item.get("lastvalue")) > last_value:
                        last_value = int(item.get("lastvalue"))
            if last_value > 0:
                filter_result[hostid] = last_value 
        return sorted(filter_result.items(), key=lambda item:item[1], reverse=True)
    
    

    def get_graphid(self, graph_name):
        if graph_name == "traffic":
            hostid_by_filter = self.get_traffic_value()
        if graph_name == "tcp_connection":
            hostid_by_filter = self.get_conn_value()
        if graph_name == "CPU utilization":
            hostid_by_filter = self.get_cpu_value()
        host_ids = [host[0] for host in hostid_by_filter]
        graph_ids = []
        d = {}
        for hostid in host_ids:
            neirong={
                    "jsonrpc": "2.0",
                    "method": "graph.get",
                    "params": {
                        "output": "extend",
                        "hostids": hostid,
                        "search": {
                            "key_": "tcp_connection"  # does't work.
                         },
                        "sortfield": "name"
                    },
                    "auth": self.authid,
                    "id": 1
            }
            response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
            for graph in response.json()['result']:
                if graph_name in graph['name']:
                    if "traffic" in graph_name:
                        v = self.from_graphid_to_itemid(graph['graphid'])
                        if not d.get('hostid'):
                            d[hostid] = [v, graph['graphid']]
                        if v > d[hostid][0]:
                            d[hostid] = [v, graph['graphid']]
                    else:
                        graph_ids.append(graph['graphid'])
        if d:
            sorted_list = sorted(d.items(), key=lambda item:item[1][0], reverse=True)
            for i in sorted_list:
                graph_ids.append(i[1][1])
        return graph_ids

    def create_screen(self, graph_name, screen_name):
        screenitems = []
        x,y= (0, 0)
        for resourceid in self.get_graphid(graph_name):
            if not x // 3:
                d = {
                    "resourcetype": 0,
                    "resourceid": resourceid,
                    "rowspan": 1,
                    "colspan": 1,
                    "x": x,
                    "y": y
                    }
                x += 1
            else:
                d = {
                    "resourcetype": 0,
                    "resourceid": resourceid,
                    "rowspan": 1,
                    "colspan": 1,
                    "x": x,
                    "y": y
                    }
                x = 0
                y += 1
            screenitems.append(d)
        if len(screenitems) >= 40:
            vsize = 40
            screenitems = screenitems[:40]
        else:
            vsize = len(screenitems)
        neirong={
                "jsonrpc": "2.0",
                "method": "screen.create",
                "params": {
                    "name": screen_name,
                    "hsize": 4,
                    "vsize": vsize,
                    "screenitems": screenitems
                },
                "auth": self.authid,
                "id": 1
            }
        response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
        print(response.text)
        print("finished.")

if __name__ == '__main__':
#    zabbixApi().create_screen("tcp_connection", "TCP_Connections")
#    zabbixApi().create_screen("traffic", "Network_Traffic")
    zabbixApi().create_screen("CPU utilization", "CPU Usage")
