# 需安裝 numpy 套件

import numpy as np
import os.path as op

from os import listdir
from os.path import isfile, isdir, join

import re


def bin2csv(in_fn, out_fn, v_type, t_res, s_res):
    '''
    in_fn  : 輸入binary檔名
    out_fn : 輸出csv檔名
    v_type : 變數類別, TT, TX, TN, RR, TD, RH, PP
    t_res  : 時間解析度 時 HR, 日 DY or 月 MN
    s_res  : 空間解析度 GFE1km, GFE2p5km
    '''
  
    #----- 從 binary file 讀入格點資料, 重點 dtype -> single precision float\
    print("input-file-17: {0}".format(in_fn))
    bin_data = np.fromfile(in_fn, dtype='float32')
    print(type(bin_data))
    print(bin_data.shape)
    #---- reshape 成 GFE1km or GFE2.5km
    if s_res == "GFE1km" :
        row, col = 650, 650
    elif s_res == "GFE2p5km" :
        row, col = 260, 260
   
  
    out_array = bin_data.reshape(row, col)

    #print(out_array)

    #---- fmt 格式應隨資料值大小, 特別是雨量的資料長度會依 hr, dy, mn 而須增加
    #---- 應只有雨量分 (hr), (dy,mn) 2種格式

    # 還須判斷變數種類

    if v_type == "RR" :
        if t_res == "HR":
            out_fmt="%6.1f"  # 長度因時間尺度而變
        elif t_res == "DY" or t_res == "MN": # 1000.8
            out_fmt="%7.1f"
    elif v_type == "TT" or v_type == "TD" :
        out_fmt="%6.1f"
    elif v_type == "PP" :  # 1009.1
        out_fmt="%7.1f"
    elif v_type == "RH" :  # 100
        out_fmt="%3.1f"

    np.savetxt(out_fn, out_array, fmt=out_fmt, delimiter=",")


if __name__ == "__main__" :
    # bin檔案所在目錄
    #path = "D:\Temp\Python"

    path = r"C:\Users\XYZ\TT"

    # 取得所有檔案與子目錄名稱
    files = listdir(path)

    #files = [files[3], files[5]]
    print(files)

    re_pattern = re.compile(".*\.bin")
  
    for f in files:

        if_match = re_pattern.match(f)

        # method 1: re
        if if_match is None:
            continue
        else:
            print("pattern-match-88: {0}".format(if_match.group(0)))

        # method 2: str slice
        #if f[-3:] != "bin":
        #  continue

        in_fn = path + "\\" + f
        print('main-infile-78: ', in_fn)
        out_fn = path + "\\" + f[:-4] + ".csv"
        print('main-outfile-80: ', out_fn)
        v_type = "TT"
        t_res = "DY"
        s_res = "GFE2p5km"
        bin2csv(in_fn, out_fn, v_type, t_res, s_res)