#!/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 getopt
import sys
import pynmea2

from gnuboat import daemon

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

# default values for command line arguments
rrdfile = "/var/lib/gnuboat/log-webservice.rrd"
shutdownfile = "/var/spool/gnuboat/shutdown.request"
logfile = "/var/log/gnuboat-nmea1983.log"
logperiod = 2
displayperiod = 5

shutdownRequested = None
nmeafile = None


def rraRows(duration, resolution, step):
    return int(round(float(duration) / rraSteps(resolution, float(step)) / float(step)))


def rraSteps(resolution, step):
    return int(round(float(resolution) / float(step)))


def createDatabase(databaseFile):
    rrdDataSources = ['DS:latitude:GAUGE:15:-90:90',
                      'DS:longitude:GAUGE:15:-180:180',
                      'DS:speedthroughwater:GAUGE:15:U:U',
                      'DS:speedoverground:GAUGE:15:U:U',
                      'DS:waterdepth:GAUGE:15:0:10000',
                      'DS:watertemperature:GAUGE:15:-10:50',
                      'DS:gpsfix:GAUGE:15:-999:3']

    step = logperiod
    # durations: each archive should contain values for in seconds
    archives = [
        {"duration": 240, "resolution": 2},
        {"duration": 3600, "resolution": 10},
        {"duration": 86400, "resolution": 60},
    ]
    rrdArchives = []
    for i in range(0, len(archives)):
        rrdArchives += ['RRA:AVERAGE:0.5:%d:%d' % (rraSteps(archives[i]["resolution"], step), rraRows(
            archives[i]["duration"], archives[i]["resolution"], step))]

    if not os.path.isfile(databaseFile):
        rrdtool.create(databaseFile,
                       "--start",
                       "N",
                       "--step",
                       str(step),
                       rrdDataSources,
                       rrdArchives)


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 "  -d --displayperiod     Timein seconds to update the display"
    print "  -o --output            File where the NMEA1983 log is stored"


def main(argv):
    global rrdfile
    global shutdownfile
    global logperiod
    global displayperiod
    global logfile
    global nmeafile

    try:
        opts, args = getopt.getopt(argv, "hr:s:l:d:o:", [
                                   "help", "rrdfile=", "shutdownfile=", "logperiod=", "displayperiod=", "output="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    for option, argument in opts:
        if option == ("-h", "--help"):
            usage()
            sys.exit()
        elif option in ("-r", "--rrdfile"):
            rrdfile = argument
        elif option in ("-s", "--shutdownfile"):
            shutdownfile = argument
        elif option in ("-l", "--logperiod"):
            logperiod = argument
        elif option in ("-d", "--displayperiod"):
            displayperiod = argument
        elif option in ("-o", "--output"):
            logfile = argument
        else:
            assert False, "unhandled option"

    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)

    createDatabase(rrdfile)

    try:
        nmeafile = open(logfile, 'a', 0)
    except IOError as error:
        print "Could not open the logfile: %s" % error
        sys.exit(2)

    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()
            waterDepth = n2kd.waterDepth()
            waterTemperature = n2kd.waterTemperature()
            gpsFix = gpsp.gpsFix()

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

            # append to log
            if gpsp.gpsFix() >= 2:
                timeUtc = gpsp.timeUtc()
                status = gpsp.status()
                latitudeDirection = gpsp.latitudeDirection()
                longitudeDirection = gpsp.longitudeDirection()
                courseOverGround = gpsp.courseOverGround()

                mode = 'N'
                if gpsFix >= 2:
                    mode = 'A'

                nmeafile.write("%s\r\n" % str(pynmea2.RMC('GN', 'RMC',
                                                          (timeUtc.strftime("%H%M%S"), status, '$%04.3f' % latitude,
                                                           latitudeDirection, '$%05.3f' % longitude, longitudeDirection,
                                                           '$%02.1f' % speedOverGround, '$%02.1f' % courseOverGround,
                                                           timeUtc.strftime("%d%m%y"), '', '', mode))))
                if n2kd.waterDepthValid():
                    nmeafile.write("%s\r\n" % str(pynmea2.DPT('SD', 'DPT',
                                                             ('%02.2f' % waterDepth, '00.00'))))

            # display data
            displayHandler.setValues(
                speedThroughWater, speedOverGround, 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:])
