import mechnet as mn
import numpy as np
import matplotlib.pyplot as plt
import h5py
import sys
sys.path.append("/home/lpyka/hierarchical_interface")
from lib.push_data import push_data_to, push_ivcat 

def get_iv_data(filepath):
    grouppaths = mn.datman.bundle_all_sub_groups(filepath, ["simulationdata"])
    simdata = mn.datman.get_simdata(filepath, grouppaths[0], readpickled=True)
    simdata_dict = simdata.get_simdata_dict()
    iv_data = np.array(simdata_dict["logged_data"]["iv"])
    return iv_data


def get_index(i, graph_num, width):
    if graph_num <= width:
        index = i
    else:
        index = i//width, i%width
    return index

def add_iv_curve(data, axs, index):
    x = data[:,1]
    y = data[:,0]
    axs[index].plot(x, y)
    return axs


def append_data_to_txt(data, seed):
    with open("ivcat.txt", 'a') as file:
        file.write(f"#seed_{seed}\n")
        for point in data:
            x, y = point 
            file.write(f"{x} {y}\n")

def clear_txt_file():
    with open("ivcat.txt", "w")  as f:
        f.write("")

if __name__ == "__main__":
    crack_lenght = input("Crack length:  ")
    base_path = f"/FASTTEMP/p7/lpyka/hierarchical_interface/5_precracked/a_{crack_lenght}"
    clear_txt_file()
    low_seed = 1000
    max_seed = 1050
    fig, axs = plt.subplots(5,10) 
    graph_num = max_seed - low_seed 
    for seed in range(low_seed, max_seed):
        file_name = f"RTS_FDB_PARSOL_SIRC-FCVC_SOG-IVCG_HFBA_CPC-NIC_-_{seed}.h5" 
        full_path = base_path + "/" + file_name
        iv_data = get_iv_data(full_path)
        i = seed - low_seed
        index = get_index(i, graph_num, 10)
        axs = add_iv_curve(iv_data, axs, index)
        append_data_to_txt(iv_data, seed)
    plt.show()
    push_ivcat(base_path) 
    print("cutoff prev")