#! /usr/bin/env cached-nix-shell
#! nix-shell -i python3 -p "with import (builtins.fetchTarball {url = "https://github.com/nixos/nixpkgs/archive/8686922e68dfce2786722acad9593ad392297188.tar.gz";}) {overlays = [(self: super: {cerb = (with super; python3.pkgs.buildPythonPackage rec {pname = \"cerbapi\"; version = \"1.0.9\"; src = python3.pkgs.fetchPypi {inherit pname version; sha256 = \"1c5xahjfb60vrwn7hj0n4s66dyzsx81gai7af564n8pkbdylcz37\";}; doCheck = false;});})];}; python3.withPackages (ps: with ps; [ cerb pydbus notify2 pymysql pyopenssl slackclient ])"

from cerbapi import Cerb
import notify2
import time
import os
import argparse

# _context: cerberusweb.contexts.ticket
# _label: [#JD-43166-193] Запрос из панели AC_225134 (Тема запроса: Перестал работать сайт)
# closed_at: 1587110403
# closed: 1587110403
# created: 1587109927
# elapsed_response_first: 476
# elapsed_resolution_first: 476
# id: 12079330
# importance: 0
# mask: JD-43166-193
# num_messages: 3
# org_id: 0
# reopen_date: 0
# spam_score: 0.0001
# spam_training: N
# status_id: 0
# subject: Запрос из панели AC_225134 (Тема запроса: Перестал работать сайт)
# updated: 1587112328
# status: open
# url: https://cerberus.intr/index.php/profiles/ticket/JD-43166-193
# group_id: 31
# bucket_id: 27
# initial_message_id: 14812768
# initial_response_message_id: 14812861
# latest_message_id: 14812903
# owner_id: 0


class Cerberus:
    def __init__(self):
        try:
            self.cerberus_key = os.environ['CERBERUS_KEY']
            self.cerberus_secret = os.environ['CERBERUS_SECRET']
        except KeyError:
            print("Check system environment variables CERBERUS_KEY and CERBERUS_SECRET")
            exit(1)

        self.api = Cerb(access_key=self.cerberus_key, secret=self.cerberus_secret,
                        base="https://cerberus.intr/index.php/rest/")
        self.group_list = {}
        self._load_groups()

    def get_tickets(self, groups, status, count=100):
        groups_string = ""
        for i, group in enumerate(groups):
            if i == 0:
                groups_string = "("
            groups_string = groups_string + group
            if i < len(groups)-1:
                groups_string = groups_string + " OR "
            else:
                groups_string = groups_string + ")"
        result = self.api.search_records('ticket', query='group:{} status:{}'.format(groups_string, status), limit=count)
        return result

    def _load_groups(self):
        self.group_list = self.api.search_records('group')

    def get_group_by_id(self, id):
        for group in self.group_list['results']:
            if group['id'] == id:
                return group['name']
        return "Undefined"

    def is_valid_group(self, name):
        for group in self.group_list['results']:
            if group['name'] == name:
                return True
        return False


def main():
    cerb = Cerberus()
    known_tickets = []

    parser = argparse.ArgumentParser(description="Cerberus notifications")
    parser.add_argument('-i', default=10, help='Update interval in seconds', type=int)
    parser.add_argument('-g', default='support@majordomo.ru,admin@majordomo.ru', help='Watching groups')
    args = parser.parse_args()

    interval_time = args.i
    watching_groups = args.g.split(",")

    for group in watching_groups:
        if not cerb.is_valid_group(group):
            print("Invalid group name: {}".format(group))
            exit(1)

    while(True):
        tickets = cerb.get_tickets(watching_groups, 'open')

        status = tickets['__status']
        if status != 'success':
            print("Error: {}".format(tickets))
            continue

        count = tickets['count']
        print("Ticket count: {}".format(count))

        result = tickets['results']
        actual_tickets = []

        for ticket in result:
            actual_tickets.append(ticket['id'])
            if ticket['id'] in known_tickets:
                continue

            notify2.init("New Tiket")
            n = notify2.Notification("New tiket in group {}: {}\n{}".format(
                cerb.get_group_by_id(ticket['group_id']),
                ticket['subject'],
                ticket['url']))
            n.set_urgency(notify2.URGENCY_CRITICAL)  # For red notification in dunst case
            n.set_timeout(30000)
            n.show()

        known_tickets = actual_tickets

        print("Known tickets: {}".format(known_tickets))
        time.sleep(interval_time)


if __name__ == '__main__':
    main()
