import numpy as np
import os,sys
import subprocess
sys.dont_write_bytecode = True

def CHECK_IF_KEY_PRESENT(key_list,inp_dict):
    inp_dict_key_list = list(inp_dict.keys())
    flag_option       = False
    for key_name_reqd in key_list:
        if key_name_reqd not in inp_dict_key_list:
            flag_option = True
            print("Input Dictionary should contain key :",key_name_reqd)

    if flag_option:
        print("Exiting the code now !!!")
        exit()


def CHECK_AND_INITIALIZE_KEY_VALUE(inp_dict,key_name,default_key_value):
    if key_name not in list(inp_dict.keys()):
        inp_dict.update({key_name:default_key_value})
    return inp_dict

def COPY_SELECTED_DICTIONARY_KEYS(inp_dict_source,key_list_to_copy,inp_dict_dest={}):
    N_key         = len(key_list_to_copy)
    for key_indx in range(N_key):
        key_name = key_list_to_copy[key_indx]
        key_val  = inp_dict_source[key_name]
        inp_dict_dest.update({key_name:key_val})
    return inp_dict_dest


def DELETE_KEY_LIST_IF_PRESENT(key_list,inp_dict,flag_print="n",method="pop"):
    inp_dict_key_list = list(inp_dict.keys())
    for key_name_reqd in key_list:
        if key_name_reqd in inp_dict_key_list:
            if method == "del":
                del inp_dict[key_name_reqd]
            elif method == "pop":
                inp_dict.pop(key_name_reqd)
            if flag_print == "y":
                print("Key :",key_name_reqd,"deleted ...")
    return inp_dict


def CONVERT_DICTIONARY_TO_LIST(inp_dict):
    inp_list = []
    key_list = inp_dict.keys()
    N_keys   = len(key_list)
    for key_indx in range(N_keys):
        key_name = key_list[key_indx] 
        key_val  = inp_dict[key_name]
        list_val = str(key_name) + ":" + str(key_val)
        inp_list.append(list_val)
    return inp_list


def READ_DICTIONARY_FROM_FILE(npy_file_path,flag_delete_file="n",rank=None,comm=None):
    data_dict = np.load(npy_file_path,allow_pickle=True,encoding='latin1').item()
    if flag_delete_file == "y":
        if rank == 0:
            print("Input dictionary read on rank =",rank)
            comm.Barrier()
            del_command = "rm -fr " + npy_file_path
            subprocess.call(del_command,shell=True)
        else:
            print("Input dictionary read on rank =",rank)
            comm.Barrier()
    return data_dict


def CONVERT_DTYPE_OBJECT_TO_DICTIONARY(data_arr,label_arr):
    """ Structure of data_arr should be as follows
    data_arr[i,0] -->> Key names / Alias
    data_arr[i,1] -->> First element of sub dictionary key_name -->> label_arr[0]
    data_arr[i,2] -->> First element of sub dictionary key_name -->> label_arr[1]

    Very Important data_arr should always be loaded with dtype = None
    data_arr        = np.genfromtxt(specie_filename,dtype=None)

    """

    assert len(label_arr) == (len(data_arr[0])-1)

    N_row     = len(data_arr)
    N_col     = len(data_arr[0])
    data_dict = {}

    for row_indx in range(N_row):
        key_name      = data_arr[row_indx][0]#.decode()
        data_sub_dict = {}
        for col_indx in range(1,N_col):
            key_name_sub_dict  = label_arr[col_indx-1]
            key_value_sub_dict = data_arr[row_indx][col_indx]
            data_sub_dict.update({key_name_sub_dict:key_value_sub_dict}) 
        data_dict.update({key_name:data_sub_dict})
    return data_dict




















