#!/usr/bin/python -u

'''
--------------------------------------------------------------------------------
    Type:           Python 3.x script
    Author:         Milan Toman (milan.v.toman@gmail.com)
    Description:    System stats

    TODO:           CPU util.


    influxDB SCHEMA:

    DB status

    ISS measure
    ----------------
      voltage | solar or capacitor | state / lqi /  | battery or future_shit |
      ----------------------------------------------------------------
      field     tag                  field   tag

    RasPI
    ----------------
      usage | disk, mem, cpu, eth, wifi %
      ------------------------------------
      field | tag



--------------------------------------------------------------------------------
            Import libraries
--------------------------------------------------------------------------------
'''
# mandatory
import requests
import sys
import os
import re
import textwrap
import argparse
import time
import datetime
import simplejson as json
import influxdb
import psutil

# optionally, future modules, locally available, I hate dependencies
from pprint import pprint
_SCRIPT_PATH = os.path.dirname(sys.argv[0])
sys.path.append(_SCRIPT_PATH + "/home/pi/test/lib")
#print(_SCRIPT_PATH + "/lib")

#import ventilLogger


'''
--------------------------------------------------------------------------------
            Define variables
--------------------------------------------------------------------------------
'''
_VERSION = 2.0
_NAME = u"Vantage Vue Decoding shite"
_LOG_DIR = _SCRIPT_PATH + '/log/'
_LOG_FILE_ROOT = re.sub(u'./', '', sys.argv[0])
_LOG_FILE = _LOG_DIR + _LOG_FILE_ROOT + u'.log'
_DEBUG_FILE = _LOG_DIR + _LOG_FILE_ROOT + u'.dbg'

influx_status_write = []

influx_host = 'localhost'
influx_port = 8086
influx_user = 'pi'
influx_pwd = 'freedavis'
status_db = 'status'

'''
--------------------------------------------------------------------------------
            Set up logging - disabled, need to enable this iin future
--------------------------------------------------------------------------------
'''


'''
--------------------------------------------------------------------------------
            Setup arguments and Options - not edited, sample shite
--------------------------------------------------------------------------------
'''
desc = u'''\
DESCRIPTION:
    Vantage Vue wireless data transfer decoder, V2
    consult http://wp.spoton.cz/2017/11/24/davis-vantague-vue-arduino-and-a-raspberry-pi-3/
    for wtf is going on
    '''
epi = u'''\
    ERROR CODES:
        ?

    EXAMPLES:
        ?

    '''
formatter = argparse.RawDescriptionHelpFormatter
arg_parser = argparse.ArgumentParser(description = desc,
                                     formatter_class = formatter,
                                     epilog = textwrap.dedent(epi))

arg_parser.add_argument('-d', '--details',
                        help = 'help',
                        action='store_true')
arg_parser.add_argument('-v', '--verbose',
                        help = 'help',
                        action='store_true')
arg_parser.add_argument('-p', '--section',
                        dest = 'section',
                        default = ['last', 'count', 'diff'],
                        choices = ['last', 'count', 'diff'],
                        nargs = '+',
                        type = str,
                        help = 'help')
arg_parser.add_argument('-s', '--snapusage',
                        help = 'help',
                        action='store_true')

args = arg_parser.parse_args()
if args.details:
    _details = True
else:
    _details = False
if args.verbose:
    _more_details = True
else:
    _more_details = False
if args.snapusage:
    _SNAP_USAGE = True
else:
    _SNAP_USAGE = False
try:
    _sections = args.sections
except:
    _sections = ['last', 'count', 'diff']
'''
--------------------------------------------------------------------------------
            Generic, standalone functions
--------------------------------------------------------------------------------
'''

# Obvious shit, set up the client class
influx_status_client = influxdb.client.InfluxDBClient(
    influx_host, influx_port, influx_user, influx_pwd, status_db
)

'''
--------------------------------------------------------------------------------
            Classes
--------------------------------------------------------------------------------
'''

class DBwriter(object):
    def __init__(self):
        __name__ = "Database writer class, Influx"

    def construct(self, connector, measurement, fields, tags):
        """ Takes values in a writes them to influxdb

        requires:   list(connector): connector with all ticks to be written
                                     at once
                    str(measurement): the measurement ID to be written
                    dict(fields): fields to be written in one tick
                    dict(tags): tags to be written with the fields

        returns:    list(result_connector)
        """
        result_connector = connector
        result_connector.append({"measurement": measurement,
                                 "fields": fields,
                                 "tags": tags}
                               )
        return result_connector

'''
--------------------------------------------------------------------------------
            Main
--------------------------------------------------------------------------------
'''
if '__main__':
    davis_writer = DBwriter()
    while True:
        averaged_cpu = 0
        # CPU stats
        for timeout in range(1,5):
            if timeout == 1:
                averaged_cpu = psutil.cpu_percent()
                mem_consumption = psutil.virtual_memory()[2]
                disk_usage = psutil.disk_usage('/')[3]
            else:
                averaged_cpu = (averaged_cpu + psutil.cpu_percent()) / 2
            time.sleep(1)
        # Write the whole blob into Influx DB
        influx_status_write = davis_writer.construct(
                influx_status_write,
                "RasPI",
                {"usage": float(averaged_cpu)},
                {"type": "cpu"}
            )
        influx_status_write = davis_writer.construct(
                influx_status_write,
                "RasPI",
                {"usage": float(mem_consumption)},
                {"type": "mem"}
            )
        influx_status_write = davis_writer.construct(
                influx_status_write,
                "RasPI",
                {"usage": float(disk_usage)},
                {"type": "disk"}
            )
        print(influx_status_write)
        influx_status_client.write_points(influx_status_write)
        influx_status_write = []
        averaged_cpu = 0
