import os
import sys
import glob
import json
import numpy as np
# sys.path.append('../../../



class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, datetime):
            return obj.__str__()
        else:
            return super(MyEncoder, self).default(obj)

def LoadJson(filename):
    if not os.path.exists(filename):
        print ('path %s does not exist'%filename)
    with open(filename,'r') as f:
        result = json.load(f)
    f.close()
    return result
    
def WriteJson(filename,dict_data):
    dirname = os.path.dirname(filename)
    if (dirname != '') and (not os.path.exists(dirname)):
        os.makedirs(dirname)
    f = open(filename, 'wt')
    json.dump(dict_data, f,sort_keys=True, indent=4,cls=MyEncoder)
    f.close()


def GenerateParameters(model_parameter_filename,model_map_parameter_filename,model='VGG'):
    if not os.path.exists(model_parameter_filename):
        print ('Invalid model_parameter_filename')
        return {}
    if not os.path.exists(model_map_parameter_filename):
        print ('Invalid model_map_parameter_filename')
        return {}
    with open(model_parameter_filename,'r') as f:
        model_parameters = json.load(f)
    f.close()
    
    with open(model_map_parameter_filename,'r') as f:
        parameter_map_dict = json.load(f)
    f.close()
   
    current_parameters = parameter_map_dict[model]
    
    model_parameter_dict = {}
    for key in current_parameters:
        if key not in model_parameters.keys():
            model_parameter_dict[key] = float('inf')
        else:
            model_parameter_dict[key] = model_parameters[key]
    return model_parameter_dict


def GenerateParameters(model_parameter_filename,model_map_parameter_filename,model='VGG'):
    if not os.path.exists(model_parameter_filename):
        print ('Invalid model_parameter_filename')
        return {}
    if not os.path.exists(model_map_parameter_filename):
        print ('Invalid model_map_parameter_filename')
        return {}
    with open(model_parameter_filename,'r') as f:
        model_parameters = json.load(f)
    f.close()
    
    with open(model_map_parameter_filename,'r') as f:
        parameter_map_dict = json.load(f)
    f.close()
   
    current_parameters = parameter_map_dict[model]
    
    model_parameter_dict = {}
    for key in current_parameters:
        if key not in model_parameters.keys():
            model_parameter_dict[key] = float('inf')
        else:
            model_parameter_dict[key] = model_parameters[key]
    return model_parameter_dict
    
