#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
    Copyright (C) 2016 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

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/www/html/webservice/data/log-webservice.rrd"
shutdownfile = "/var/spool/gnuboat/shutdown.request"
logperiod = 1
displayperiod = 5

shutdownRequested = None

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

  def latitude(self):
    return self._session.fix.latitude
   
  def longitude(self):
    return self._session.fix.longitude

  def speedOverGround(self):
    return self._session.fix.speed
   
  def gpsFix(self):
    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

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

  rrdArchives = [ 'RRA:AVERAGE:0.5:1:60',
                  'RRA:AVERAGE:0.5:5:720',
                  'RRA:AVERAGE:0.5:15:1440',
                  'RRA:AVERAGE:0.5:30:1440',
                  'RRA:AVERAGE:0.5:60:1440' ]

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

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)
  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)
  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)
  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)
  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)
  draw.text((x, y + rowHeightTitles), str(gpsFix), fill=BLACK, font=fontValues)
  
  epd.display(image)
  epd.update()

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

  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)

  if epdEnabled:
    epd = EPD()
    epd.clear()

  gpsp = GpsdPoller()
  try:
    gpsp.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 = random.randrange(0, 10)
      speedOverGround = gpsp.speedOverGround()
      waterDepth = random.randrange(1, 30) + 0.5;
      waterTemperature = random.randrange(15, 25) + 0.5;
      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))
      # update display, if needed
      if epdEnabled and round(time.time(),0) % displayperiod == 0:
        displayValues(epd, 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

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