#!/usr/bin/env python

'''
@author: Viktor Petersson
For the latest version, visit https://github.com/vpetersson/munin_zendesk
'''

import requests, json, sys, os, pickle, zendesk_helper

username = zendesk_helper.username
password = zendesk_helper.password 
subdomain = zendesk_helper.subdomain
cache_folder = zendesk_helper.cache_folder
cache_file_path = os.path.join(cache_folder, 'zendesk_tickets.pkl')

if len(sys.argv) == 2 and sys.argv[1] == "autoconf":
    print 'yes'

elif len(sys.argv) == 2 and sys.argv[1] == "config":
    print 'graph_title Zendesk Tickets'
    print 'graph_vlabel count'
    print 'graph_category zendesk'
    print 'total_open.label Open Tickets'
    print 'total_open.type GAUGE'
    print 'total_new.label New Tickets'
    print 'total_new.type GAUGE'    
    print 'total_pending.label Pending Tickets'
    print 'total_pending.type GAUGE'
    print 'total_solved.label Solved Tickets'
    print 'total_solved.type GAUGE'
    print 'graph_args --base 1000'

# Retreive the real data
elif len(sys.argv) == 2 and sys.argv[1] == "refreshcache":

    # Define variables
    all_tickets = []
    ticketsOpen = 0
    ticketsClosed = 0
    ticketsNew = 0
    ticketsPending = 0
    ticketsSolved = 0
    
    cache_file = open(cache_file_path, 'wb')
    
    tickets = "https://" + str(subdomain) + ".zendesk.com/api/v2/tickets.json"
    fetch = requests.get(tickets, auth=(username, password))
    if fetch.status_code != 200:
        print 'Received non-200 status from Zendesk.'
        sys.exit(1)
    result = json.loads(fetch.content)

    # Ops, there's another page with tickets. Let's keep fetching.
    while result['next_page'] != None:
        fetch_more = requests.get(str(result['next_page']), auth=(username, password))
        result = json.loads(fetch_more.content)
        all_tickets += result['tickets']

    if all_tickets:
        tickets = all_tickets
    else:
        tickets = result['tickets']
        
    # Do the math
    for i in tickets:
        if i['status'] == 'open':
            ticketsOpen += 1
        elif i['status'] == 'closed':
            ticketsClosed += 1
        elif i['status'] == 'new':
            ticketsNew += 1
        elif i['status'] == 'pending':
            ticketsPending += 1
        elif i['status'] == 'solved':
            ticketsSolved += 1
                
    # Gather the result and write them to the cache
    result  = { 'ticketsOpen' : ticketsOpen, 'ticketsClosed' : ticketsClosed, 'ticketsNew' : ticketsNew, 'ticketsPending' : ticketsPending, 'ticketsSolved' : ticketsSolved}
    pickle.dump(result, cache_file)
    cache_file.close()

else:
    # Fetch the result from the local cache
    if os.path.isfile(cache_file_path):
        cache_file = open(cache_file_path, 'rb')
        result = pickle.load(cache_file)
        ticketsOpen = result['ticketsOpen']
        ticketsNew = result['ticketsNew']
        ticketsPending = result['ticketsPending']
        ticketsSolved = result['ticketsSolved']
        cache_file.close()
        
        # Report the result
        print 'total_open.value ' + str(ticketsOpen)
        print 'total_new.value ' + str(ticketsNew)
        print 'total_pending.value ' + str(ticketsPending)
        print 'total_solved.value ' + str(ticketsSolved)
    else:
        print 'No local cache available. Exiting.'
        sys.exit(1)
