import numpy as np
import h5py
from contextlib import contextmanager
import os
from time import time


def save(fname, dict_to_save):
    with h5py.File(fname, "w") as f:
        for key, data in dict_to_save.items():
            f.create_dataset(key, data=data)


def eval_psnr(fig1, fig2):
    if np.issubdtype(fig1.dtype, np.unsignedinteger):
        fig1 = fig1.astype(np.float32)
    def my_rms(x):
        return np.sqrt(np.mean((x.flatten()) ** 2))

    pamp = 255  # was: np.amax(fig1)
    rms = my_rms(fig1 - fig2)
    if rms == 0.0:
        psnr_ = np.inf
    else:
        psnr_ = 20.0 * np.log10(pamp / rms)
    return psnr_


@contextmanager
def interprocess_lock(lockfile):
    try:
        gotten = False
        while not gotten:
            try:
                os.mkdir(lockfile)
                gotten = True
            except FileExistsError:
                time.sleep(0.01)
        yield
    finally:
        os.rmdir(lockfile)
