#!/usr/bin/env python3

import gpsd
import os
import time
import logging
import sys
from configobj import ConfigObj
from timezonefinder import TimezoneFinder
#import daemon
#import subprocess

# SetUp logging
logging.basicConfig(filename='/var/log/gpsctl.log',format='%(asctime)s: %(levelname)s - %(message)s',level=logging.INFO)

### Read global config
# Reference
# https://stackoverflow.com/a/42568457/2147823
# https://stackoverflow.com/a/54148952/2147823
conf = ConfigObj('/etc/bdr.conf') # GPS_DAEMON_SLEEP variable and other global
###

ovrl_cmd = '/usr/local/bin/gstd-client element_set cam_src_pipe location text '
tracking = '/var/log/gpstrack.log'
tz_obj=TimezoneFinder(in_memory=True)
#tz_obj=TimezoneFinder()

### Connect to the local gpsd ###
gpsd.connect() # gpsd.connect(host="127.0.0.1", port=123456)
location_current = 0

def deleteContent(fName):
    open(fName, "w").close()

def daemon_status():
    with open(conf['BDR_STATUS_FIFO'],'a') as f_status: # or status_file
        f_status.write("GPS=1")
        f_status.close()

def GPSONOFF_state():
    with open('/proc/bdr/gpsonoff','r') as f_state:
        state=f_state.read()
        f_state.close()
#        state_int=int(float(state))
    if state.rstrip() != str(1):
        logging.debug('GPS ON')
        return True
    else:
        time.sleep(int(conf['GPS_DAEMON_SLEEP']))
        logging.debug('GPS OFF')
        return False

def timezone_refresh(current_lat,current_lon,datenew):
#    logging.info('Update TZ')
    # Get current TZ
    tz_file=open("/etc/timezone","r")
    current_tz=tz_file.read()
    tz_file.close()
    logging.info('System TZ is: %s', current_tz)

    # Get GPS TZ
    gps_tz=tz_obj.certain_timezone_at(lng=current_lon, lat=current_lat)
    logging.debug('GPS TZ is: %s', gps_tz)

    if gps_tz.strip() != current_tz.strip():
        os.system("timedatectl set-timezone " + str(gps_tz))
        os.system("timedatectl set-local-rtc 0")
        newdate="date -s" + "\"" + str(datenew) + "\""
        os.system(newdate)
        os.system("hwclock -w")
        logging.info('Refresh TZ to %s Date is %s', gps_tz, datenew)
    else:
        logging.debug('Current TZ is the same: %s Date is %s', current_tz, datenew)
        newdate="date -s" + "\"" + str(datenew) + "\""
        os.system(newdate)

def update_ovrl(_location):
#    logging.info('Update GSTD overlay')
    update_data = (ovrl_cmd + _location)
    os.system(update_data)

def gps_parse():
    global location_current
    packet = gpsd.get_current()
    logging.debug('GPS poll packet: %s' % (packet))

    if packet.mode >= 2:
        latitude=packet.lat
        longtitude=packet.lon
        location = str(packet.lat) + " " + str(packet.lon)

        if location_current != location:
            location_current = location
###     Loging data                     ###
            logging.info('%s: GPS mode %s with sats %s %s',str(packet.get_time(local_time=True)),packet.mode,packet.sats,packet.position())
###     Write GPS Mode 2/3 and data     ###

            with open('/proc/bdr/gpslock','w') as gpslock:
                    #gpslock.write("%d" packet.mode)
                    print("1", file=gpslock) ### Remove due to missing state code in MCU print(packet.mode, file=gpslock)
                    gpslock.close()

            with open ('/home/user/bidentifier/gpslocation','w') as gpslocation:
                logging.debug('Save Position')
                print(str(location_current), file=gpslocation)
                gpslocation.close()
            with open ('/proc/bdr/gpslocation','w') as gpslocation:
                logging.debug('Save Position')
                print(str(location_current), file=gpslocation)
                gpslocation.close()

###     Keep track to file "tracking"   ###
            with open (tracking,'a') as trackingfile:
                trackingfile.write("%s: %s   %s\n" % ( str(packet.get_time(local_time=True)),packet.position(),packet.map_url()))
                trackingfile.close()
###     Check&Set TZ    ###
            getdateandtime=str(packet.get_time(local_time=True))
            getdate=getdateandtime.split(' ',1)[1]
            timezone_refresh(latitude,longtitude,getdateandtime)
    else:
        logging.debug('No GPS lock, mode=%s', str(packet.mode))
        deleteContent('/proc/bdr/gpslock')
        deleteContent('/home/user/bidentifier/gpslocation')

def run():
#    daemon_status()
    while True:
        while GPSONOFF_state():
            logging.info('---')
            conf = ConfigObj('/etc/bdr.conf') # GPS_DAEMON_SLEEP variable and other global vars
            logging.debug(conf['GPS_DAEMON_SLEEP'] + " seconds time interval")
            time.sleep(int(conf['GPS_DAEMON_SLEEP']))
            try:
                gps_parse()
            except Exception as str_error:
                logging.warning('Error \"%s\"',str_error)
                continue

if __name__ == "__main__":
    run()

### reference
# https://stackoverflow.com/a/20985318/2147823
# https://stackoverflow.com/a/48726480/2147823
###
