#!/usr/bin/env python3

import os
import pyodbc
import sys
import unittest

sys.path.append(
    os.path.abspath(
        os.path.join(os.path.dirname(__file__), '..', 'src', 'usm')
    )
)
from usmd import database
from utils import *


class TestUSM(unittest.TestCase):
    def setUp(self):
        self.conn = pyodbc.connect(**database)

    def test_database(self):
        campus, building, room = 'TEST', 'TEST', 'TEST'
        device, property, value = 'TEST', 'TEST', 'TEST'

        try:
            self.conn.execute(INSERT_CAMPUS, (campus, campus))
        except Exception as e:
            self.fail('Campus insert failed: %s' % e)
        campus_id, = self.conn.execute(GET_CAMPUS_ID, (campus,)).fetchone()
        self.assertIsInstance(campus_id, int)

        try:
            self.conn.execute(INSERT_BUILDING, (campus_id, building, building))
        except Exception as e:
            self.fail('Building insert failed: %s' % e)
        building_id, = self.conn.execute(GET_BUILDING_ID, (campus_id, building)).fetchone()
        self.assertIsInstance(building_id, int)

        try:
            self.conn.execute(INSERT_ROOM, (building_id, room, room))
        except Exception as e:
            self.fail('Room insert failed: %s' % e)
        try:
            self.conn.execute(UPDATE_ROOM, (building_id, room))
        except Exception as e:
            self.fail('Room update failed: %s' % e)
        room_id, = self.conn.execute(GET_ROOM_ID, (building_id, room)).fetchone()
        self.assertIsInstance(room_id, int)

        try:
            self.conn.execute(INSERT_DEVICE, (room_id, device, device))
        except Exception as e:
            self.fail('Device insert failed: %s' % e)
        try:
            self.conn.execute(UPDATE_DEVICE, (room_id, device))
        except Exception as e:
            self.fail('Device update failed: %s' % e)
        device_id, = self.conn.execute(GET_DEVICE_ID, (room_id, device)).fetchone()
        self.assertIsInstance(device_id, int)

        try:
            self.conn.execute(INSERT_PROP, (device_id, property, property, value))
        except Exception as e:
            self.fail('Property insert failed: %s' % e)
        try:
            self.conn.execute(UPDATE_PROP, (value, device_id, property))
        except Exception as e:
            self.fail('Property update failed: %s' % e)
        property_id, = self.conn.execute(GET_PROP_ID, (device_id, property)).fetchone()
        self.assertIsInstance(property_id, int)

    def tearDown(self):
        self.conn.rollback()
        self.conn.close()


if __name__ == '__main__':
    unittest.main()
