#!/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 gps
import time
import threading
import re
import os
import dateutil.parser
import datetime
from pytz import timezone
import pytz
import getopt
import sys
import socket
import json

try:
  from EPD import EPD
  from PIL import Image
  from PIL import ImageDraw
  from PIL import ImageFont
  epdEnabled = True
except:
  epdEnabled = False

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"
logperiod = 2
displayperiod = 5

shutdownRequested = None
latitude = None
longitude = None
speedThroughWater = None
speedOverGround = None
waterDepth = None
waterTemperature = None
gpsFix = None

# Copied from https://gist.github.com/wolfg1969/4653340
class GpsdPoller(threading.Thread):
  def __init__(self):
    threading.Thread.__init__(self)
    try:
      self._session = gps.gps(mode=gps.WATCH_ENABLE)
    except:
      self._session = None
      self._running = False
      return
    self._currentValue = None
    self._running = True

  def latitude(self):
    if self._session == None:
      return 0
    return self._session.fix.latitude
   
  def longitude(self):
    if self._session == None:
      return 0
    return self._session.fix.longitude

  def speedOverGround(self):
    if self._session == None:
      return 0
    return self._session.fix.speed
   
  def gpsFix(self):
    if self._session == None:
      return 0
    return self._session.fix.mode
   
  def stop(self):
    self._running = False
   
  def run(self):
    global logperiod
    try:
      while self._running:
        self._currentValue = self._session.next()
        time.sleep(float(logperiod)/2.0)
    except StopIteration:
      pass

"""@class N2kdPoller
"""
class N2kdPoller(threading.Thread):
  def __init__(self):
    threading.Thread.__init__(self)
    self._serverHost = "raspi"
    self._serverPort = 2597
    self._timeout = 1.5
    self._speedThroughWater = 0
    self._distanceLog = 0
    self._distanceLogTrip = 0
    self._waterDepth = 0
    self._waterTemperature = 0
    self._running = True

  def speedThroughWater(self):
    return self._speedThroughWater
   
  def distanceLog(self):
    return self._distanceLog

  def distanceLogTrip(self):
    return self._distanceLogTrip

  def waterDepth(self):
    return self._waterDepth
   
  def waterTemperature(self):
    return self._waterTemperature

  def _loadData(self):
    n2kdSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    n2kdSocket.connect((self._serverHost, self._serverPort))
    response = ""
    while 1:
      data = n2kdSocket.recv(1024)
      if not data:
        break
      response += data
    n2kdSocket.close()
    data = json.loads(response)
    
    descriptions = [ "Water Depth", "Speed", "Environmental Parameters", "Distance Log" ]
    
    for key in data:
      entryKeys = data[key].keys()
      if len(entryKeys) != 2:
        print "Malformed json n2kd response? %s" % response
      else:
        if data[key]["description"] in descriptions:
          entryKey = entryKeys[1]
          lineKeys = data[key][entryKey].keys()
          if "fields" not in lineKeys:
            print "No fields entry. Malformed json n2kd response in %s" % data[key][entryKey]
          else:
            fields = data[key][entryKey]["fields"]
            # try water depth (NEED TO APPLY OFFSET?)
            if "Depth" in fields:
              if data[key][entryKey]["description"] == "Water Depth":
                self._waterDepth = fields["Depth"]
            # try speed
            if "Speed Water Referenced" in fields:
              self._speedThroughWater = fields["Speed Water Referenced"]
            # try sea temperature
            if "Temperature Source" in fields and "Temperature" in fields:
              if fields["Temperature Source"] == "Sea Temperature":
                self._waterTemperature = fields["Temperature"]
            # try log
            if "Log" in fields:
              self._distanceLog = fields["Log"]
            if "Trip Log" in fields:
              self._distanceLogTrip = fields["Trip Log"]

  def _serverUrl(self):
    return "http://%s:%d/" % (self._serverHost, self._serverPort)
   
  def stop(self):
    self._running = False
   
  def run(self):
    global logperiod
    try:
      while self._running:
        self._loadData()
        time.sleep(float(logperiod)/2.0)
    except StopIteration:
      pass

"""@class DisplayHandler
"""
class DisplayHandler(threading.Thread):
  def __init__(self, displayperiod):
    threading.Thread.__init__(self)
    try:
      self._epd = EPD()
    except:
      epdEnabled = False
      return
    self._epd.clear()
    self._updatePeriod = displayperiod
    self._running = True
    
  def stop(self):
    self._running = False
    
  def run(self):
    global latitude
    global longitude
    global speedThroughWater
    global speedOverGround
    global waterDepth
    global waterTemperature
    global gpsFix

    try:
      while self._running:
        self.displayValues(epd, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix)
        time.sleep(self._updatePeriod)
    except StopIteration:
      pass

  def displayValues(epd, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix):
    if not epdEnabled:
      return

    # requires dejavu package!!!!
    fontValues = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 34)
    fontTitles = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 24)

    # initially set all white background
    image = Image.new('1', epd.size, WHITE)
    width, height = image.size

    rowHeightTitles = 25
    rowHeightValues = float(height - 2 * rowHeightTitles - 3 * marginVertical) / 2.0
    columnWidthUnit = 30
    columnWidthValues = int(float(width - 3 * marginHorizontal - 2 * columnWidthUnit) / 2.0)

    draw = ImageDraw.Draw(image)
    # draw.rectangle((0, 0, width, height), fill=WHITE, outline=WHITE)

    x = marginHorizontal
    y = marginVertical
    draw.text((x, y), "STW", fill=BLACK, font=fontTitles)
    if speedThroughWater is not None:
      draw.text((x, y + rowHeightTitles), str(speedThroughWater), fill=BLACK, font=fontValues)
    draw.text((x + columnWidthValues, y + rowHeightTitles * 1.4), "kts", fill=BLACK, font=fontTitles)

    x = x + marginHorizontal + columnWidthValues + columnWidthUnit
    draw.text((x, y), "SOG", fill=BLACK, font=fontTitles)
    if speedOverGround is not None:
      draw.text((x, y + rowHeightTitles), str(speedOverGround), fill=BLACK, font=fontValues)
    draw.text((x + columnWidthValues, y + rowHeightTitles * 1.4), "kts", fill=BLACK, font=fontTitles)

    x = marginHorizontal
    y = y + rowHeightTitles + rowHeightValues + marginVertical
    draw.text((x, y), "Depth", fill=BLACK, font=fontTitles)
    if waterDepth is not None:
      draw.text((x, y + rowHeightTitles), str(waterDepth), fill=BLACK, font=fontValues)
    draw.text((x + int(float(columnWidthValues) / 1.5), y + rowHeightTitles * 1.4), "m", fill=BLACK, font=fontTitles)

    x = x + marginHorizontal + columnWidthValues + columnWidthUnit
    draw.text((x, y), "Water", fill=BLACK, font=fontTitles)
    if waterTemperature is not None:
      draw.text((x, y + rowHeightTitles), str(waterTemperature), fill=BLACK, font=fontValues)
    draw.text((x + int(float(columnWidthValues) / 1.5), y + rowHeightTitles * 1.4), "C", fill=BLACK, font=fontTitles)

    x = int((x + marginHorizontal + columnWidthValues) * 0.93)
    draw.text((x, y), "Fix", fill=BLACK, font=fontTitles)
    if gpsFix is not None:
      draw.text((x, y + rowHeightTitles), str(gpsFix), fill=BLACK, font=fontValues)
  
    epd.display(image)
    epd.update()

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]"
  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"

def main(argv):
  global rrdfile
  global shutdownfile
  global logperiod
  global displayperiod
  global latitude
  global longitude
  global speedThroughWater
  global speedOverGround
  global waterDepth
  global waterTemperature
  global gpsFix

  try:                                
    opts, args = getopt.getopt(argv, "hr:s:l:d:", ["help", "rrdfile=", "shutdownfile=", "logperiod=", "displayperiod="]) 
  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
    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)

  displayHandler = None
  if epdEnabled:
    displayHandler = DisplayHandler(displayperiod)

  gpsp = GpsdPoller()
  n2kd = N2kdPoller()
  try:
    gpsp.start()
    n2kd.start()
    # gpsp now polls every .2 seconds for new data, storing it in self.current_value
    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))
      #check for shutdown request
      checkShutdownRequest(shutdownfile)
       
  except (KeyboardInterrupt, SystemExit): #when you press ctrl+c
    gpsp.stop()
    gpsp.join() # wait for the thread to finish what it's doing
    n2kd.stop()
    n2kd.join()
    if displayHandler is not None:
      displayHandler.stop()
      displayHandler.join() # wait for the thread to finish what it's doing

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