import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
import ezrun
import hashlib
import os
import dill

def cache_get_key(fun,*args):
    return fun.__name__+hashlib.md5((str(args)).encode('UTF8')).hexdigest()

class ezcache:
    def __init__(self,directory='/home/domke/work1/divide_and_couple'):
        self.directory = directory

    def run(self,fun,*args,name=None,resid=None,ncores=1,mem=100,submit=None,hours=12,minutes=0,force=False):
        fname = self.directory + '/' + cache_get_key(fun,args)
        if (force is not True) and os.path.isfile(fname):
            print('results already exist - returning')
            return
        def myfun(*args):
            import dill
            rez = fun(*args)
            print('rez (insidem myfun)',rez)
            with open(fname,'wb') as f:
                dill.dump(rez,f)

        ezrun.run(myfun,*args,name=name,resid=resid,ncores=ncores,mem=mem,submit=submit,hours=hours,minutes=minutes)

    def get(self,fun,*args):
        import warnings
        warnings.filterwarnings("ignore", message="numpy.dtype size changed")
        warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
        fname = self.directory + '/' + cache_get_key(fun,args)
        if os.path.isfile(fname):
            with open(fname, 'rb') as f:
                return dill.load(f)
        else:
            error_msg = 'results do not exist for: ' + fun.__name__ + str(args)
            print('fname:',fname)
            raise Exception(error_msg)

    def wait_for_complete(self):
        ezrun.wait_for_complete()
