
"""
 This utility is to plot a field extract from T04 file.
 It has been tested under Windows 10.
 It needs to use "viewdat.exe" as it underlying tool to decode T04 file.
 Please make sure you can access viewdat.exe program.

 Revision History:
 - Rev. 0.1 --  2020.05.10
 
"""

import os
import subprocess
import numpy as np
import re
import sys
import matplotlib
import matplotlib.pyplot as plt

Usage = f"""
Usage:
   {sys.argv[0]} <T04filename> key=number [YLabel=<label>] [Title=<Title>] [T1=n1] [T2=n2] [-h] [-dnn:mm] [KeyTime=x]
   where: 
    * <T04filename>: required, the T04 file that you want to plot
    * -dnn:mm: optional, default using "-d35:2", to specify which T04 record and sub-record you want to plot
    * key=number: required, to specify which key in -dnn:mm subrecord to be plotted
    * YLable="???": optional, the label you want to put on the plot Y-axix
    * Title="???": optional, the Title you want to put on the plot, default is mapped to the key name from T04 file  
    * T1=n1: optional, the beginning time to plot
    * T2=n2: optional, the ending time to plot
    * -h: the help, also show the key mapping of the records
    * KeyTime=x: optional, the index of key.TIME or key.Secs in the "-m -h" display
        
   Example1: 
     {sys.argv[0]} <file> key=69 YLabel="YawRate(deg/s)" Title="Data from T04" T1=0 T2=596997 -d35:2
"""

#viewDatCmdPath = f"c:\\Util\\"  # the viewdat.exe file location
viewDatCmdPath = ""  # the viewdat.exe file location
T04Records = "-d35:2"           # the default T04 records to be plotted
KeyTime = 2  # the "% key.TIME is at key#2 for "-d35:2" record
             # user should enter this parameter for different record.
             # for example, "-d35:4" key.TIME is at 5

if (len(sys.argv) < 2):  # need at least a T04 file
   print(Usage)
   exit()

fileName = sys.argv[1]

if not os.path.exists(fileName):
   print(f"\r\n\tfile {fileName} does not exist!\r\n")
   exit()

keyNum = None
y_label = None
Title  = None
T1 = 0
T2 = 0
allKeys = False
KeyTime = None

#### Get the parameters from the command #####   
for arg in sys.argv:
  if arg == '-h':
    allKeys = True
  if re.search(r"^-d", arg):
    T04Records = arg 
    
  if KeyTime == None:
    argData = re.search(r"KeyTime=(\d+)", arg)
    if argData:
       KeyTime = int(argData.group(1))
       continue
      
  if keyNum == None:
    argData = re.search(r"key=(\d+)", arg)
    if argData:
       keyNum = int(argData.group(1))
       continue
  if y_label == None:
    argData = re.search(r"YLabel=(.*)", arg)
    if argData:
       y_label = argData.group(1)
       continue
  if Title == None:
    argData = re.search(r"Title=(.*)", arg)
    if argData:
       Title = argData.group(1)
       continue
  if T1 == 0:
    argData = re.search(r"T1=(\d+)", arg)
    if argData:
       T1 = int(argData.group(1))
       continue
  if T2 == 0:
    argData = re.search(r"T2=(\d+)", arg)
    if argData:
       T2 = int(argData.group(1))
       continue
       
###### Set some defaults ########
if Title==None:
   Title = fileName 

if keyNum == None:
   allKeys = True 
else:
   keyNum = keyNum - 1 

if KeyTime == None and T04Records == "-d35:2":
   KeyTime = 2

data = []
xTime = []
startT = 0
currentT = 0

##################################
def getKeyNameFromT04(k):
    cmd = f"{viewDatCmdPath}viewdat.exe {T04Records} -m -h {fileName}"
    
    p = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    if (p.returncode == 0):
        if allKeys:
          lines = p.stdout.splitlines()
          for line in lines:
             if re.search(r"^\% key\.", line):
                print(line)
        else:
          searchStr = r'\% key\.(.*)=\s{1,2}' + f'{k + 1} ;'       
          keyData = re.search(searchStr, p.stdout)
          if (keyData):
            return keyData.group(1).strip()   
    return None
##################################


##################################
def getDataFromT04():
    global T1, T2, currentT, startT
    cmd = f"{viewDatCmdPath}viewdat.exe {T04Records} -m {fileName}"
    p = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    if (p.returncode == 0):
        lines = p.stdout.splitlines()
        for line in lines:
          if re.search(r'^%', line):
             continue;
          lineItems = line.split('\t')
          currentT = float(lineItems[KeyTime - 1]) # the seconds of week is at key#1
          if (startT == 0) :
             startT = currentT
          if (T1 != 0 and currentT < T1):
             continue
          if (T2 != 0 and currentT > T2):
             break
          #print(f"{currentT}, {lineItems[keyNum]}")
          #if lineItems[keyNum] == "Nan":
          #   break
          xTime.append(currentT)
          data.append(float(lineItems[keyNum]))
    else:
        print(f"failed command code :{p.returncode}")    

##################################

keyName = getKeyNameFromT04(keyNum)
if allKeys:
  print(Usage)
  exit()

if keyName == None:
   print(f"\r\n!!! Does not have the record {keyNum + 1} !!!!\r\n")
   exit()

if KeyTime == None:
   print(f"\r\n!!! You need to provide KeyTime index !!!!\r\n")
   exit()
 
   
if Title == fileName:
    Title = keyName + "(" + fileName + ")"  

getDataFromT04()

if len(xTime) > 0: 
    xData = np.array(xTime) 
    yData = np.array(data)
    duration = int(currentT - startT)

    plt.plot(xData, yData, 'b')  # blue color
    plt.xlabel(f"Seconds of the week, span {duration} seconds")
    plt.ylabel(y_label)
    plt.title(Title)

    plt.show()
else:
    print(f"\r\n\t No Data available for key={keyNum + 1}")






