#!/usr/bin/env python3

"""
<sphinx>
influxdb-query
--------------

Queries an InfluxDB database and compares results.

Parameters:

- host
- port (default: 8086)
- user
- password
- database
- query
- expected: A json serialized result (not pretty formatted)

Example of JSON serialized result for query 'select value from cpu_load_short;':

.. code:: json

    [
        [
            {"time": "2009-11-10T23:00:10Z", "value": 10.64},
            {"time": "2009-11-10T23:00:20Z", "value": 20.64},
            {"time": "2009-11-10T23:00:30Z", "value": 30.64},
            {"time": "2009-11-10T23:00:40Z", "value": 40.64}
        ]
    ]

</sphinx>
"""

import os
import sys
import influxdb
import itertools
import json
from typing import Tuple


class InfluxDBQueryCheck(object):
    client: influxdb.InfluxDBClient

    def __init__(self, host: str, port: int, user: str, password: str, database: str):
        self.client = influxdb.InfluxDBClient(host=host, port=port)
        self.client.switch_user(user, password)
        self.client.switch_database(database)

    def main(self, query: str, expected: str) -> Tuple[bool, str]:
        results = self.client.query(query)
        encoded = json.dumps(list(results))

        if expected not in encoded:
            self.client.close()
            return False, "Expected '{actual}' to contain '{expectation}'".format(expectation=expected, actual=encoded)

        self.client.close()
        return True, "Query results are matching"


if __name__ == '__main__':
    try:
        app = InfluxDBQueryCheck(
            host=os.environ['HOST'],
            port=int(os.getenv('PORT', 8086)),
            user=os.environ['USER'],
            password=os.environ['PASSWORD'],
            database=os.environ['DATABASE']
        )

        status, message = app.main(
            query=os.environ['QUERY'],
            expected=os.environ['EXPECTED']
        )
    except KeyError as attribute:
        print('Missing environment variable: {}'.format(attribute))
        sys.exit(1)

    print(message)
    sys.exit(0 if status else 1)
