# oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
# This is a small extension of climate1 program
# it also extract the station name from the file header
# oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo

# ----------------------------------------------------------------
# Simple helper function
# ----------------------------------------------------------------

# turns date format YYYYMMDD into DD.MM.YYYY
def getDate( dateStr ):
    # Date YYYYMMDD
    year = dateStr[0:4]
    month = dateStr[4:6]
    day = dateStr[6:8]
    return day + "." + month + "." + year

def isLastInHeader( line ):
    return line[0:5] == "STAID"

def extractStation( line, stationKeyword ):
    position = line.index( stationKeyword )
    position += len(stationKeyword )
    # rest of the line is supposed to identify the station
    return line[position: ]

# ----------------------------------------------------------------
# The coldestDay funcion depends on the exact format of the data.
# Check the data file visually to see how the data are organized.
# ----------------------------------------------------------------
def coldestDay( fileName ):
    # named constants do help
    dateColumn = 2
    temperColumn = 3
    qualityColumn = 4
    qualityValid = 0
    qualitySuspect = 1
    qualityMissing = 9
    stationName = "" # unknown yet
    stationKeyword = "station"
    celsius_degree_sign= u'\u2103' # discover via google

    # start reading
    file = open( fileName, "r" )

    # process the file header
    while True:
        line = file.readline()
        # check for the station name:
        if stationName == "" and stationKeyword in line:
            stationName = extractStation( line, stationKeyword )
        if isLastInHeader( line ): break

    minTemper = 10000 # start with big temperature
    dateMinTemper = 0

    # process all lines
    while True:
        line = file.readline()
        # carefully process possible empty lines
        if line == None or line.strip(" ") == "":
            break

        # extract info from a text line
        lineVals = line.split(",")
        date =  lineVals[dateColumn]
        temper = int( lineVals[temperColumn] )
        quality = int( lineVals[qualityColumn] )

        # do not accept dubious data
        if quality != qualityValid:
            continue

        if temper <= minTemper:
            minTemper = temper
            dateMinTemper = date
            print( temper, date )

    file.close()
    print("The lowest temperature", \
          " in", stationName, "was ", \
          minTemper/10, " ", celsius_degree_sign, \
          " and it was on ", \
          getDate( dateMinTemper ), ".", sep = "" )
    #end of coldestDay


path ="d:\\Iskola\\PGE2019\\data\\"
fname = "TG_STAID000169.txt"
fname = "TG_STAID000027.txt"

coldestDay( path + fname )