#!/usr/bin/env python
#
#  Copyright 2017 Trimble Inc.
#
import sys
import subprocess
try:
    from urllib import urlretrieve
except:
    from urllib.request import urlretrieve
import shutil
import datetime
import os

def check_run(cmd):
    subprocess.check_call(cmd,shell=True)


# Convert the GPS week/seconds into correc YYYY/MM/DD/HH etc. Returns a
# time object we can use to get details of time
def weeksecondstotime(gpsweek,gpsseconds):
  datetimeformat = "%Y-%m-%d %H:%M:%S"
  epoch  = datetime.datetime.strptime("1980-01-06 00:00:00",datetimeformat)
  offset = datetime.timedelta(days=(gpsweek*7),seconds=(gpsseconds))
  now = epoch + offset
  return now


def getGVRSdata( timeStart, timeStop, latDeg, lonDeg ):
  """Create CMRx.T04 with CMRx data.
  timeStart = datetime.datetime start time
  timeStop = datetime.datetime end time
  latDeg = rough latitude [deg]
  latDeg = rough longitude [deg]
  """

  # Download the T04 files with CMRx data embedded. We use the Start/Stop
  # times we extracted from the DUT T0X file. Loop around for each hour,
  # this may need refining as it looks like we are downloading more data
  # than we need.
  if os.path.isfile("RTXObs.T02"):
    os.remove("RTXObs.T02")
  dest_file = open("RTXObs.T02",'ab') # 'a'ppend in 'b'inary mode

  # back up timeStart to nearest hour mark - we grab files in hour
  # increments below
  timeStart -= datetime.timedelta( minutes=timeStart.minute,
                                   seconds=timeStart.second,
                                   microseconds=timeStart.microsecond)
  processedFirst = False
  while (timeStart <= timeStop):
    year  = str(timeStart.year)
    month = str(timeStart.month).zfill(2)
    day   = str(timeStart.day).zfill(2)
    hour  = str(timeStart.hour).zfill(2)

    if(processedFirst == False):
      if(     (lonDeg >= 128) and (lonDeg <= 146)
          and (latDeg >=  29) and (latDeg <=  45) ):
        # Very crude rectangle to represent Japan. We are logging
        # an RTX-Fast correction stream from a test network in Japan. So
        # for receivers in this area use this stream. Note the rectangle
        # is really crude so other places will be included
        print("Using Japan stream\n")
        CMRxePrefix = "5035K69800"
        FileType    = "T04"
        Server      = "proton.eng.trimble.com/data_drive2/T01.QZSS/"
        ThirtyMinFiles = False
      # Starting the beginning of Dec 2016 we also log data from a
      # different stream. This alternate stream is supposed to also
      # include Galileo. Based on the start time select the appropriate
      # files
      elif(    (timeStart.year > 2016)
            or ( (timeStart.year == 2016) and (timeStart.month == 12) ) ):
        print("Using www.trimblertx.net:2104/RTXNet stream\n")
        CMRxePrefix = "5027437243"
        FileType    = "T04"
        Server      = "fermion.eng.trimble.com/data_drive/T01.Nov3/"
        ThirtyMinFiles = True
      else:
        print("Using standard stream\n")
        CMRxePrefix = "4950409062"
        FileType    = "T02"
        Server      = "fermion.eng.trimble.com/data_drive/T01.Nov2/"
        ThirtyMinFiles = True

    print(CMRxePrefix, FileType, Server)
    print(year, month, day, hour)

    # Download the *00.T02 and *30.T02 (Hour and half-hour) files)
    hourFile = CMRxePrefix + year + month + day + hour + "00." + FileType
    urlretrieve("http://" + Server + hourFile, hourFile)
    if(ThirtyMinFiles):
      halfFile = CMRxePrefix + year + month + day + hour + "30." + FileType
      urlretrieve("http://" + Server + halfFile, halfFile)

    if not processedFirst:
      processedFirst = True
    # concat to RTXObs.T02
    shutil.copyfileobj(open(hourFile,'rb'), dest_file)
    if(ThirtyMinFiles):
      shutil.copyfileobj(open(halfFile,'rb'), dest_file)

    # Clean up
    os.remove(hourFile)
    if(ThirtyMinFiles):
      os.remove(halfFile)

    timeStart = timeStart + datetime.timedelta(seconds=3600)

  dest_file.close()
  # Remove Obs and positions as we are going to concat with the DUT
  # file. As remove any logged data bits to make the file size more
  # manageble.
  check_run("t0x2t0x -i98 RTXObs.T02 CMRx.T04")
  os.remove("RTXObs.T02")
