import sys
import chardet
import re
import matplotlib.pyplot as plt

from binparser import type_map, load_bin_file, get_data
from analyze_RIGAKU import parse_text_file


text_file = 'sk250606-2-Eagle-Bi5w-S150c50w-Sub200c-25min-oradw.txt'
bin_file = 'sk250606-2-Eagle-Bi5w-S150c50w-Sub200c-25min-oradw.raw'
endian = 'little'

argv = sys.argv
nargs = len(argv)
if nargs > 1: text_file = argv[1]
if nargs > 2: bin_file = argv[2]
#if nargs > 4: endian = argv[3]

print()
print(f"{text_file=}")
print(f"{bin_file=}")
print(f"{endian=}")


var_inf = [
    { 's': '00000084:00000054', 'offset': 84, 'vartype': 'str', 'varname': 'User1', 'value': 'User1', 'eps': 0.0 },
#    { 's': '00000104:00000068', 'offset': 104, 'vartype': 'str', 'varname': 'sk250606-1-Eagle-Bi5PB', 'value': 'sk250606-1-Eagle-Bi5PB', 'eps': 0.0 },
    { 's': '00000104:00000068', 'offset': 104, 'vartype': 'str', 'varname': 'Sample', 'value': 'sk250606-1-Eagle-Bi5PB', 'eps': 0.0 },
    { 's': '00000228:000000e4', 'offset': 228, 'vartype': 'str', 'varname': 'Goniometer', 'value': 'SmartLab(In-plane)', 'eps': 0.001 },
#    { 's': '00000228:000000e4', 'offset': 228, 'vartype': 'str', 'varname': 'SmartLab(In-plane)', 'value': 'SmartLab(In-plane)', 'eps': 0.0 },
    { 's': '00000228:000000e4', 'offset': 228, 'vartype': 'str', 'varname': 'Condition', 'value': 'SmartLab(In-plane)', 'eps': 0.0 },
    { 's': '00000884:00000374', 'offset': 884, 'vartype': 'str', 'varname': 'Cu_K-beta', 'value': 'Cu_K-beta', 'eps': 0.0 },
    { 's': '00000948:000003b4', 'offset': 948, 'vartype': 'str', 'varname': 'Soller_slit_5.0deg', 'value': 'Soller_slit_5.0deg', 'eps': 0.0 },
    { 's': '00001040:00000410', 'offset': 1040, 'vartype': 'str', 'varname': 'Monochromater', 'value': 'None', 'eps': 0.001 },
#    { 's': '00001040:00000410', 'offset': 1040, 'vartype': 'str', 'varname': 'None', 'value': 'None', 'eps': 0.0 },
#    { 's': '00001132:0000046c', 'offset': 1132, 'vartype': 'str', 'varname': 'SC-70', 'value': 'SC-70', 'eps': 0.0 },
    { 's': '00001132:0000046c', 'offset': 1132, 'vartype': 'str', 'varname': 'Condition2', 'value': 'SC-70', 'eps': 0.0 },
#    { 's': '00002172:0000087c', 'offset': 2172, 'vartype': 'str', 'varname': 'IhOut of Plane', 'value': 'IhOut of Plane', 'eps': 0.0 },
    { 's': '00002172:0000087c', 'offset': 2172, 'vartype': 'str', 'varname': 'Condition3', 'value': 'IhOut of Plane', 'eps': 0.0 },
    { 's': '00002174:0000087e', 'offset': 2174, 'vartype': 'str', 'varname': 'Comments', 'value': 'Out of Plane', 'eps': 0.001 },
    { 's': '00002206:0000089e', 'offset': 2206, 'vartype': 'str', 'varname': '入射スリット', 'value': '1.000mm', 'eps': 0.001 },
#    { 's': '00002206:0000089e', 'offset': 2206, 'vartype': 'str', 'varname': '受光スリット1', 'value': '1.000mm', 'eps': 0.001 },
#    { 's': '00002206:0000089e', 'offset': 2206, 'vartype': 'str', 'varname': '受光スリット2', 'value': '1.000mm', 'eps': 0.001 },
#    { 's': '00002206:0000089e', 'offset': 2206, 'vartype': 'str', 'varname': '1.000mm', 'value': '1.000mm', 'eps': 0.0 },
#    { 's': '00002294:000008f6', 'offset': 2294, 'vartype': 'str', 'varname': '入射スリット', 'value': '1.000mm', 'eps': 0.001 },
    { 's': '00002294:000008f6', 'offset': 2294, 'vartype': 'str', 'varname': '受光スリット1', 'value': '1.000mm', 'eps': 0.001 },
#    { 's': '00002294:000008f6', 'offset': 2294, 'vartype': 'str', 'varname': '受光スリット2', 'value': '1.000mm', 'eps': 0.001 },
#    { 's': '00002294:000008f6', 'offset': 2294, 'vartype': 'str', 'varname': '1.000mm', 'value': '1.000mm', 'eps': 0.0 },
#    { 's': '00002382:0000094e', 'offset': 2382, 'vartype': 'str', 'varname': '入射スリット', 'value': '1.000mm', 'eps': 0.001 },
#    { 's': '00002382:0000094e', 'offset': 2382, 'vartype': 'str', 'varname': '受光スリット1', 'value': '1.000mm', 'eps': 0.001 },
    { 's': '00002382:0000094e', 'offset': 2382, 'vartype': 'str', 'varname': '受光スリット2', 'value': '1.000mm', 'eps': 0.001 },
#    { 's': '00002382:0000094e', 'offset': 2382, 'vartype': 'str', 'varname': '1.000mm', 'value': '1.000mm', 'eps': 0.0 },
    { 's': '00002962:00000b92', 'offset': 2962, 'vartype': 'float32', 'varname': 'Start', 'value': 10.0, 'eps': 0.001 },
#    { 's': '00002962:00000b92', 'offset': 2962, 'vartype': 'float32', 'varname': 'x[0]', 'value': 10.0, 'eps': 0.001 },
    { 's': '00002966:00000b96', 'offset': 2966, 'vartype': 'float32', 'varname': 'Stop', 'value': 90.0, 'eps': 0.001 },
    { 's': '00002970:00000b9a', 'offset': 2970, 'vartype': 'float32', 'varname': 'Step', 'value': 0.01, 'eps': 0.001 },
    { 's': '00003154:00000c52', 'offset': 3154, 'vartype': 'int16', 'varname': 'ndata', 'value': 8001, 'eps': 0.001 },
    { 's': '00003158:00000c56', 'offset': 3158, 'vartype': 'float32', 'varname': 'y[0]', 'value': 20.0, 'eps': 0.001 },
    { 's': '00003162:00000c5a', 'offset': 3162, 'vartype': 'float32', 'varname': 'y[1]', 'value': 24.0, 'eps': 0.001 },
    { 's': '00003166:00000c5e', 'offset': 3166, 'vartype': 'float32', 'varname': 'y[2]', 'value': 22.0, 'eps': 0.001 },
    { 's': '00003170:00000c62', 'offset': 3170, 'vartype': 'float32', 'varname': 'y[3]', 'value': 21.0, 'eps': 0.001 },
    { 's': '00003174:00000c66', 'offset': 3174, 'vartype': 'float32', 'varname': 'y[4]', 'value': 19.0, 'eps': 0.001 },
#    { 's': '00003178:00000c6a', 'offset': 3178, 'vartype': 'float32', 'varname': 'y[0]', 'value': 20.0, 'eps': 0.001 },
#    { 's': '00003190:00000c76', 'offset': 3190, 'vartype': 'float32', 'varname': 'y[1]', 'value': 24.0, 'eps': 0.001 },
#    { 's': '00003194:00000c7a', 'offset': 3194, 'vartype': 'float32', 'varname': 'y[2]', 'value': 22.0, 'eps': 0.001 },
    ]    
    
def read_bin_file(bin_file):
    bin_data = load_bin_file(bin_file)
    ilast = len(bin_data)

    vars_bin = {}
    offset_data = None
    offset_step = None
    for d in var_inf:
        varname = d["varname"]
        vartype = d["vartype"]
        if vartype == "str":
            size = ilast
        else:
            size = type_map[vartype][1]
        offset  = d["offset"]
        value_bin = get_data(bin_data, offset, size, vartype, endian = endian, varname = varname)
            
        vars_bin[varname] = value_bin
        if varname == "y[0]":
            offset_data = offset
            data_type = vartype
            data_size = size
        if varname == "y[1]":
            offset_step = offset - offset_data

    start = vars_bin["Start"]
    step  = vars_bin["Step"]
    ndata = vars_bin["ndata"]
    print("offset data:", offset_data)
    print("offset step:", offset_step)
    print("X data parameters:", start, step, ndata)

    x_list = []
    y_list = []
    for i in range(ndata):
        value_bin = get_data(bin_data, offset_data + i * offset_step, data_size, data_type, endian = endian)
        x_list.append(start + i * step)
        y_list.append(value_bin)

    return vars_bin, x_list, y_list

def main():
    print()
    print(f"Read text file [{text_file}]")
    inf, x_list, y_list = parse_text_file(text_file)
    vars_text = {}
    for d in inf:
        varname = d["varname"]
# 'x[0]'などは別に読み込むので飛ばす
        if '[' in varname: continue
        vars_text[varname] = d["value"]
#    for varname, value in vars_text.items():
#        print(f"  {varname}: {value}")

    print()
    print(f"Read raw file [{bin_file}]")
    vars_bin, x_list, y_list = read_bin_file(bin_file)
    for varname, value_bin in vars_bin.items():
# 'x[0]'などは別に読み込むので飛ばす
        if '[' in varname:
            pass
        else:
            print(f"  {varname:<30}\t{value_bin:<30}\t{vars_text.get(varname, None)}")

    plt.figure(figsize=(8, 5))
    plt.plot(x_list, y_list, linestyle='-', color='blue')
    plt.title(bin_file)
    plt.xlabel("2Theta")
    plt.ylabel("Intensity")
    plt.tight_layout()
    plt.show()

    var_inf

if __name__ == '__main__':
    main()
    