#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
    Copyright (C) 2016 - 2017 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import rrdtool
import random
import re
import os
import time
import dateutil.parser
import datetime
from pytz import timezone
import pytz
import argparse
import sys
import pynmea2
import traceback

from gnuboat import daemon

WHITE = 1
BLACK = 0
marginVertical = 10
marginHorizontal = marginVertical

# default values for command line arguments
rrdfile = "/var/lib/gnuboat/gnuboat.rrd"
shutdownfile = "/var/spool/gnuboat/shutdown.request"
logdir = "/var/log/gnuboat"
logperiod = 2
logverbose = False
logsystemtime = False
displayperiod = 5

shutdownRequested = None
nmeafile = None
nmeaFileDate = None


def checkShutdownRequest(shutdownFile):
    global shutdownRequested
    # have look for new shutdown requests
    if os.path.isfile(shutdownFile):
        with open(shutdownFile, "r") as fileHandler:
            shutdownStart = fileHandler.read().strip()
        os.remove(shutdownFile)
        shutdownRequested = dateutil.parser.parse(shutdownStart)
    # check existing shutdown requests
    if shutdownRequested is not None:
        currentTime = datetime.datetime.now()
        currentTime = currentTime.replace(tzinfo=pytz.utc)
        if (currentTime - shutdownRequested) > datetime.timedelta(seconds=0):
            os.system("sudo shutdown -h now")


def usage():
    print "Usage of gnuboat daemon:"
    print "  gnuboat -r PATH_TO_RRD_DATABAE_FILE -s PATH_TO_SHUTDOWN_REQUEST_FILE [-l [LOG_UPDATE_PERIOD] [-d DISPLAY_UPDATE_PERIOD] [-o PATH_TO_NMEA1983_LOG]"
    print ""
    print "  -h  --help              Display this help"
    print "  -r  --rrdfile           Path to the rrd database used by the webservice to serve the clients"
    print "  -s  --shutdownfile      Path to the shutdown request file, used by the webservice to request a shutdown of the system running gnuboat"
    print "  -l  --logperiod         Time in seconds to update the logs"
    print "  -lv --log-verbose       Log verbose information to nmea log file (Enables -ls and adds RMC sentences, with invalid GPS state, on non fixes"
    print "  -ls --log-system-time   Add to enable prefixing every logline with the system time (Default off)"
    print "  -d  --displayperiod     Timein seconds to update the display"
    print "  -o  --output            Directory where the log files are stored (e.g. the NMEA0183 log files)"

def log(gpsFix, gpsTime, gpsStatus, latitude, latitudeDirection, longitude,
        longitudeDirection, courseOverGround, speedOverGround, waterDepth, waterTemperature, transducerValid, logVerbose, logSystemTime):
    global logdir
    global nmeafile
    global nmeaFileDate

    # Only log, if we have a gps fix
    if gpsFix < 2:
        if not logVerbose:
            return
        gpsStatus = 'V'
        mode = 'N'
        if gpsTime is None:
            gpsTime = datetime.datetime.utcnow()
    
    nmeaFileDateShould = datetime.datetime.utcnow().strftime("%Y-%m-%d")
    mode = 'A'
    if nmeafile == None or nmeaFileDate is None or nmeaFileDate != nmeaFileDateShould:
        if nmeafile:
                nmeafile.close()
        try:
            nmeaFileDate = nmeaFileDateShould
            nmeaLogFile = "nmea0183-%s.log" % nmeaFileDate
            nmeafile = open("%s/%s" % (logdir, nmeaLogFile), 'a', 0)
        except IOError as error:
            print "Could not open the logfile: %s" % error
            sys.exit(2)

    latitude = degreesDecimalToNmea(latitude)
    longitude = degreesDecimalToNmea(longitude)

    logstring = "%s\r\n" % str(pynmea2.RMC('GN', 'RMC',
                                                  (gpsTime.strftime("%H%M%S"), gpsStatus,
                                                   '%02d%s' % (latitude['degrees'], latitude['minutes'])
                                                   latitudeDirection,
                                                   '%03d%s' % (longitude['degrees'], longitude['minutes']),
                                                   longitudeDirection,
                                                   '%04.1f' % speedOverGround, '%04.1f' % courseOverGround,
                                                   gpsTime.strftime("%d%m%y"), '', '', mode)))
    if logsystemtime:
        logstring = "%s: %s" % (datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"), logstring)

    try:                
        nmeafile.write(logstring)
    except:
        print "Failed writing to logfile %s" % nmeaLogFile
        print(traceback.format_exc())

    if transducerValid:
        nmeafile.write("%s\r\n" % str(pynmea2.DPT('SD', 'DPT', ('%05.2f' % waterDepth, '00.00'))))
        nmeafile.write("%s\r\n" % str(pynmea2.MTW('YX', 'MTW', ('%04.1f' % waterTemperature, 'C'))))

def degreesDecimalToNmea(decimalDegrees):
    degrees = math.floor(decimalDegrees)
    minutes = 60.0 * (decimalDegrees - degrees)
    return { 'degrees': degrees, 'minutes': minutes}

def main(argv):
    global rrdfile
    global shutdownfile
    global logperiod
    global logverbose
    global logsystemtime
    global displayperiod
    global logdir
    global nmeafile

    parser = argparse.ArgumentParser(description="Collects the data from canboat and gpsd and writes them to the rrd database and the nmea log file")
    parser.add_argument('-r', '--rrdfile', dest='rrd_file', metavar='rrd_file', type=str,
                        help='Path to the rrd database used by the webservice to serve the clients', default=rrdfile)
    parser.add_argument('-s', '--shutdownfile', dest='shutdown_file', metavar='shutdown_file', type=str,
                        help='Path to the shutdown request file, used by the webservice to request a shutdown of the system running gnuboat', default=shutdownfile)
    parser.add_argument('-lp', '--logperiod', dest='log_period', metavar='log_period', type=int,
                        help='Time in seconds to update the logs', default=logperiod)
    parser.add_argument('-lv', '--log-verbose', action='store_true', dest='log_verbose',
                        help='Log verbose information to nmea log file (Enables -ls and adds RMC sentences, with invalid GPS state, on non fixes (Default off)')
    parser.add_argument('-ls', '--log-system-time', action='store_true', dest='log_system_time',
                        help='Add to enable prefixing every logline with the system time (Default off)')
    parser.add_argument('-d', '--displayperiod', dest='display_period', metavar='display_period', type=int,
                        help='Time in seconds to update the display', default=displayperiod)
    parser.add_argument('-o', '--output', dest='output', metavar='output', type=str,
                        help='Directory where the log files are stored (e.g. the NMEA0183 log files)', default=logdir)
    arguments = parser.parse_args(argv)
   
    if arguments.rrd_file is not None:
        rrdfile = arguments.rrd_file
    if arguments.shutdown_file is not None:
        shutdownfile = arguments.shutdown_file
    if arguments.log_period is not None:
        logperiod = arguments.log_period   
    if arguments.log_verbose is not None:
        logverbose = arguments.log_verbose
        logsystemtime = True
    if arguments.log_system_time is not None and arguments.log_verbose is None:
        logsystemtime = arguments.log_system_time
    if arguments.display_period is not None:
        displayperiod = arguments.display_period
    if arguments.output is not None:
        logdir = arguments.output

    if not os.path.exists(os.path.dirname(rrdfile)):
        print "rrd database directory not found %s" % os.path.dirname(rrdfile)
        print ""
        usage()
        sys.exit(2)

    if not os.path.exists(os.path.dirname(shutdownfile)):
        print "Shutdown request directory not found %s" % os.path.dirname(shutdownfile)
        print ""
        usage()
        sys.exit(2)

    if logperiod < 1:
        print "Log period must be >= 1"
        print ""
        usage()
        sys.exit(2)

    if displayperiod < 1 or displayperiod < logperiod:
        print "Display period must be >= 1 and could not be faster than log period"
        print ""
        usage()
        sys.exit(2)

    daemon.rrd_create_database(rrdfile, logperiod)

    if os.path.isfile(shutdownfile):
        os.remove(shutdownfile)

    displayHandler = daemon.DisplayHandler(displayperiod)

    gpsp = daemon.GpsdPoller(logperiod)
    n2kd = daemon.N2kdPoller(logperiod)
    try:
        gpsp.start()
        n2kd.start()
        while True:
            # In the main thread, every logPeriod seconds print the current
            # value
            time.sleep(logperiod)
            latitude = gpsp.latitude()
            longitude = gpsp.longitude()
            speedThroughWater = n2kd.speedThroughWater()
            speedOverGround = gpsp.speedOverGround()
            courseOverGround = gpsp.courseOverGround()
            waterDepth = n2kd.waterDepth()
            waterTemperature = n2kd.waterTemperature()
            gpsFix = gpsp.gpsFix()

            # update rrd database for the webservice
            daemon.rrd_update(rrdfile, "N:%s:%s:%s:%s:%s:%s:%s:%s" % (
                latitude, longitude, speedThroughWater, speedOverGround, courseOverGround, waterDepth, waterTemperature, gpsFix))

            # append to log
            log(gpsFix, gpsp.timeUtc(), gpsp.status(), latitude, gpsp.latitudeDirection(),
                longitude, gpsp.longitudeDirection(), courseOverGround, speedOverGround,
                waterDepth, waterTemperature, n2kd.waterDepthValid(), logverbose, logsystemtime)
            
            # display data
            displayHandler.setValues(
                speedThroughWater, speedOverGround, courseOverGround, waterDepth, waterTemperature, gpsFix)

            # check for shutdown request
            checkShutdownRequest(shutdownfile)

    except (KeyboardInterrupt, SystemExit):  # when you press ctrl+c
        if nmeafile:
            nmeafile.close()
        if gpsp.ident is not None:
            gpsp.stop()
            gpsp.join()  # wait for the thread to finish what it's doing
        if n2kd.ident is not None:
            n2kd.stop()
            n2kd.join()
        if displayHandler.ident is not None:
            displayHandler.stop()
            # wait for the thread to finish what it's doing
            displayHandler.join()

if __name__ == "__main__":
    main(sys.argv[1:])
