#!/usr/local/bin/python
"""This program is used to collect DDN Temperatures.
Author: Coady I Kerner
Email: coady.kerner@gmail.com
"""

from __future__ import print_function
from ddn.sfa.api import *
import sqlite3
import time

program_defaults = { 'controller': '14k01-1',
                     'user': 'user',
                     'password': 'user',
                     'dbfile': '/home/coady/projects/ddn-api/temperature.db',  
                   }

def parse_options():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("-u", "--user",
                        dest="username",
                        default=program_defaults['user'],
                        action='store',
                        help="Username for the account. Default: %(default)s")

    parser.add_argument("-p", "--password",
                        dest="password",
                        default=program_defaults['password'],
                        action='store',
                        help="Password for the account. Default: %(default)s")

    parser.add_argument("-c", "--controller",
                        dest="controller",
                        default=program_defaults['controller'],
                        action='store',
                        help="DDN controller. Default: %(default)s")

    parser.add_argument("--db",
                        dest="dbfile",
                        default=program_defaults['dbfile'],
                        action='store',
                        help="Database file. Default: %(default)s")

    parser.add_argument("-v", "--verbose",
                        dest="verbose",
                        default=False,
                        action='store_true',
                        help="Run in verbose mode. Default: %(default)s")

    parser.add_argument("-D", "--debug",
                        dest="debug",
                        default=False,
                        action='store_true',
                        help="Print Debugging Information. Default: %(default)s")

    args = parser.parse_args()
    return args

def db_connect():
    """Connects to the database.

    Args:
	None

    Returns:
	db - Sqlite database object.
        sql - Sqlite database object.

    Raises:
	Nothing

    """
    epoch_time = int(time.time())

    if args.debug:
       print('Connecting to database.')
    try:
       db = sqlite3.connect(args.dbfile)
    except:
       if args.debug:
          print('Error  connecting to database.')
    if args.debug:
       print('Cursor Declaration')
    sql = db.cursor()
    return (db, sql)

def create_temperatures_table(sql):
    """Creates temperature table.

    Args:
	sql - Sqlite database object.

    Returns:
	Nothing

    Raises:
	Nothing

    """
    epoch_time = int(time.time())

    try:
       sql.execute('''
          create table if not exists
          temperatures(ts bigint not null,
             controller text not null,
             enclosure int not null,
             sensor int not null,
             temperature int not null); ''')
       if args.debug:
          print('Temperatures table created.')
    except db.Error, e:
       if args.debug:
          print('Error: ',e.args[0])

def db_disconnect(db):
    """Disconnects from the database.

    Args:
	db - Sqlite database object.

    Returns:
	Nothing

    Raises:
	Nothing

    """
    epoch_time = int(time.time())

    if args.debug:
       print('Committing the SQL')
    db.commit()
    if args.debug:
       print('Closing the database.')
    db.close()

def check_temperature(sql):
    """Checks temperature health status.

    Args:
        sql - Sqlite database object.

    Returns:
	Nothing

    Raises:
	Nothing

    """
    epoch_time = int(time.time())
    idx = 0
    while True:
        try:
            enclosure = SFAEnclosure.get(Index=idx)
            t = enclosure.getTemperatureSensors()
            try:
                len(t)
            except:
                if args.verbose:
                   print(idx,'No temperature sensors.')
            else:
                if len(t) >= 0:
                   for dindx in range (len(t)):
                      try:
                         sql.execute("insert into temperatures (ts, controller, enclosure, sensor, temperature) values (?,?,?,?,?);", (epoch_time, args.controller, idx, dindx, t[dindx].CurrentReading))
                      except db.Error, e:
                         print('Error :', e.args[0])
        except:
            break

        idx = idx + 1

if __name__ == '__main__':
   args = parse_options()

   (db, sql) = db_connect()

   create_temperatures_table(sql)

   APIConnect("https://"+args.controller, auth=(args.username, args.password))

   check_temperature(sql)   

   APIDisconnect()

   db_disconnect(db)
