# -*- coding: utf-8 -*-

# -- stdlib --
import json

# -- third party --
import requests

# -- own --
from backend.common import register_backend, Backend

# -- code --


@register_backend
class VictorOpsBackend(Backend):
    def send(self, user, event):
        if 'victorops' not in user:
            return

        url = user['victorops']
        routing_key = event['related_groups'][0]

        # status: PROBLEM OK EVENT FLAPPING TIMEWAIT ACK
        if event['status'] in ('PROBLEM', 'EVENT'):
            msg_type = 'CRITICAL'
        elif event['status'] in ( 'OK', 'TIMEWAIT'):
            msg_type = 'RECOVERY'
        elif event['status'] in ( 'ACK' ):
            msg_type = 'ACK'
        else:
            msg_type = 'INFO'

        resp = requests.post(
            url + '/' + routing_key,
            headers={'Content-Type': 'application/json'},
            timeout=10,
            data=json.dumps({
                'entity_id': event['title'],
                'entity_display_name': event['title'],
                'priority': event['level'],
                'message_type': msg_type,
                'state_message': event['text'],
            }),
        )
        if not resp.ok:
            raise Exception(resp.json())

@@ -336,16 +336,33 @@
 orops'%5D%0A
+        try:%0A    
         
@@ -386,16 +386,8 @@
 nt%5B'
-related_
 grou
@@ -393,16 +393,68 @@
 ups'%5D%5B0%5D
+%0A        except:%0A            routing_key = 'default'
 %0A%0A      
@@ -710,20 +710,16 @@
 s'%5D 
-in (
+==
  'ACK'
- )
 :%0A  

fix groups key