import sys
import numpy as np
import mechnet as mn
import shutil
from multiprocessing import Pool
sys.path.append("/home/lpyka/hierarchical_interface/")
from lib.push_data import push_data_to, copy_runfile_to 

def rerun_simulation(restart_data_zipped):
    seed = restart_data_zipped[0]
    filepath = restart_data_zipped[1]
    path_to_simdata_group = restart_data_zipped[2]
    targetdirectory = restart_data_zipped[3]
    simulationparameters = mn.datman.get_restart_simdata(filepath,path_to_simdata_group,readpickled=True)

    #regenerate fitting simulation object
    #automatic construction based on filename and included documentation
    simulation = mn.datman.get_restart_simulation_object(filepath, path_to_simdata_group)
    
    #restart the simulation; if needed hidden_parameters (typically Python
    #objects like shared variables for communication between parallel processes)
    #reinitialize those and provide them here
    simdata = simulation.restart_simulation(simulationparameters, maximum_runtime=2*85800)
    simdata_dict = simdata.get_simdata_dict()
    
    #get a network descriptor from reading the provided file (allows for simple use of the
    #same function for saving data as beforehand)
    network_descriptor_dict = mn.datman.get_restart_parameter_documentation(filepath, path_to_simdata_group)
    mn.datman.save_simulation_output(network_descriptor_dict, simdata_dict, simulation.simulationname, simulation.simulationdoc,
                                     suffix=str(seed), overwritemode = True, targetdirectory = targetdirectory)
    print("done with sim of seed", seed)
    return (network_descriptor_dict, simdata_dict, simulation.simulationname, simulation.simulationdoc)

if __name__ == "__main__":
    list_of_seeds =  []
    offset = 5
    crack_length = 20
    restart_data_zipped = []

    for seed in range(1000, 1001):

        targetdirectory = f"/FASTTEMP/p7/lpyka/hierarchical_interface/6_precrack_density_offset/a_{crack_length}/"
        filepath = targetdirectory + f"RTS_FDB_PARSOL_SIRC-FCVC_SOG-IVCG_HFBA_CPC-NIC_-_{seed}.h5"
        grouppath_bundle = mn.datman.bundle_all_sub_groups(filepath, ["simulationdata"], flaglist=[["partial", True]])
        path_to_simdata_group = grouppath_bundle[0]
        restart_data_zipped.append([seed, filepath, path_to_simdata_group, targetdirectory])
    rerun_simulation(restart_data_zipped[0])
    with Pool(1) as p:
        results = p.map(rerun_simulation, restart_data_zipped)
    destination = f"/FASTTEMP/p7/lpyka/hierarchical_interface/6_precrack_density_offset/a_{crack_length}"
    #for data in results:
    #    mn.datman.save_simulation_output(data[0], data[1], data[2], data[3], targetdirectory=destination, suffix="", overwritemode=False)
    #print(data[1]["current_data"]["stiffnessmatrix"].toarray())
    copy_runfile_to(runfile_name=__file__, destination=destination)
    print(f"done with crack_length {crack_length}")
    print("\nRun successfull.")

