#!/usr/bin/env python3

import contextlib
import datetime
import json
import logging
import pyodbc
import time

import snpplib

logging.basicConfig(format='[%(asctime)s,%(filename)s,%(levelname)s] %(message)s',
                    datefmt='%Y-%m-%d %H:%M')

ALARM_CODE = 99
SNPP_PORT = 444

@contextlib.contextmanager
def SNPP(host='localhost', port=SNPP_PORT, debuglevel=1):
    snpp = snpplib.SNPP(host, port, debuglevel)

    try:
        yield snpp
    except:
        raise
    else:
        snpp.quit()
    finally:
        snpp.close()

def get_alert(database, id):
    query = '''
        SELECT c.ALTNAME as campus, b.ALTNAME as building, b.INFO as building_notes,
               r.ALTNAME as room, r.INFO as room_notes, d.ALTNAME as device,
               p.ALTNAME as property, p.ALERTSTATUS as status, p.ALERTTYPE as type

        FROM tblCampus c
        INNER JOIN tblBuilding b ON c.id = b.idCampus
        INNER JOIN tblRoom r ON b.id = r.idBuilding
        INNER JOIN tblDevice d ON r.id = d.idRoom
        INNER JOIN tblProperties p ON d.id = p.idDevice

        WHERE p.id = ?
    '''

    with pyodbc.connect(**database) as conn:
        return conn.execute(query, id).fetchone()

def send_alert(server, alert):
    now, format = time.time(), "%Y-%m-%d %H:%M:%S"
    timestamp = datetime.datetime.fromtimestamp(now).strftime(format)
    
    message = [
        '!!!-Alert-!!!',
        'Campus         : %s',
        'Building       : %s',
        'Room           : %s',
        'Device         : %s',
        'Property       : %s',
        'Timestamp      : ' + timestamp
    ]

    if alert.building_notes is not None:
        note = 'Building Notes : %s' % alert.building_notes
        message.append(note)

    if alert.room_notes is not None:
        note = 'Room Notes     : %s' % alert.room_notes
        message.append(note)

    message = '\n'.join(message)
    message = message % (alert.campus, alert.building, alert.room,
                         alert.device, alert.property)

    with SNPP(**server) as snpp:
        snpp.pager(5551212)
        snpp.data(message)
        snpp.send()

if __name__ == '__main__':
    import sys
    id = sys.argv[1]

    try:
        with open('/etc/usm/config.json') as config:
            config = json.load(config)
    except Exception:
        # use local config for development
        with open(os.path.join('..', '..', 'etc', 'config.json')):
            config = json.load(config)

    try:

        alert = get_alert(config['database'], id)

        if alert.type == ALARM_CODE:
            send_alert(config['alarm_server'], alert)
    
    except Exception as e:
        logging.warning(e)
