from os.path import basename
import os
import numpy as np
from skimage import exposure
from skimage.io import imsave
from czifile import imread as read_czi
from glob import glob
import matplotlib.pyplot as plt
import read_lif


def get_image(img_name):
    c = 0
    im = read_czi(img_name)
    img_zstack = im[0, 0, 0, c, :, :, :, 0]
    img = np.max(img_zstack, axis=0)
    p2, p98 = np.percentile(img, (10, 99))
    img_rescale = exposure.rescale_intensity(img, in_range=(p2, p98))
    img_rescale = exposure.equalize_adapthist(img_rescale)
    return img_rescale


def mass_conv(czi_files):
    for czi in czi_files:
        try:
            fname = czi.rsplit('.')[-2].rsplit('/')[-1]
            savename = '{0}/still_images/{1}.png'.format(
                "/Users/hughesn/Google Drive/PHD/Mobility analysis", fname)
            if not os.path.exists('{0}/still_images/'.format("/Users/hughesn/Google Drive/PHD/Mobility analysis")):
                os.makedirs(
                    '{0}/still_images/'.format("/Users/hughesn/Google Drive/PHD/Mobility analysis"))
            im = get_image(czi)
            imsave(savename, im)
            print(savename)
        except Exception as e:
            print(e)
            print('Err: {0}'.format(czi))
        continue


# folder1 = "/Users/hughesn/Microscopy Images/Effector images/2018-12-06"
# folder2 = "/Users/hughesn/Microscopy Images/Effector images/2018-12-20"
# folder3 = "/Users/hughesn/Microscopy Images/Effector images/2018-12-21"


# folders = {}

# for f in [folder1, folder2, folder3]:
#     czi_files = glob('{0}/*.czi'.format(f))
#     folders[f] = czi_files


def get_lif_images(img_name):
    reader = read_lif.Reader(img_name)
    series = reader.getSeries()
    imgs = []
    for s in series:
        chosen = s
        image = chosen.getFrame()
        img = np.max(image, axis=2)
        p2, p98 = np.percentile(img, (10, 99))
        img_rescale = exposure.rescale_intensity(img, in_range=(p2, p98))
        img_rescale = exposure.equalize_adapthist(img_rescale)
        imgs.append(img)
    return imgs


def mass_lif_conv(folder, outdir):
    for f in glob("{0}/*.lif".format(folder)):
        path = "{0}/{1}/".format(outdir, basename(f))
        if not os.path.exists(path):
            os.makedirs(path)
        images = get_lif_images(f)
        for idx, i in enumerate(images):
            imsave(path+str(idx)+'.png', i)

from os.path import basename
import os
import numpy as np
from skimage import exposure
from skimage.io import imsave
from czifile import imread as read_czi
from glob import glob
import matplotlib.pyplot as plt
import read_lif


def get_image(img_name):
    c = 0
    im = read_czi(img_name)
    img_zstack = im[0, 0, 0, c, :, :, :, 0]
    img = np.max(img_zstack, axis=0)
    p2, p98 = np.percentile(img, (10, 99))
    img_rescale = exposure.rescale_intensity(img, in_range=(p2, p98))
    img_rescale = exposure.equalize_adapthist(img_rescale)
    return img_rescale


def mass_conv(czi_files):
    for czi in czi_files:
        try:
            fname = czi.rsplit('.')[-2].rsplit('/')[-1]
            savename = '{0}/still_images/{1}.png'.format(
                "/Users/hughesn/Google Drive/PHD/Mobility analysis", fname)
            if not os.path.exists('{0}/still_images/'.format("/Users/hughesn/Google Drive/PHD/Mobility analysis")):
                os.makedirs(
                    '{0}/still_images/'.format("/Users/hughesn/Google Drive/PHD/Mobility analysis"))
            im = get_image(czi)
            imsave(savename, im)
            print(savename)
        except Exception as e:
            print(e)
            print('Err: {0}'.format(czi))
        continue


# folder1 = "/Users/hughesn/Microscopy Images/Effector images/2018-12-06"
# folder2 = "/Users/hughesn/Microscopy Images/Effector images/2018-12-20"
# folder3 = "/Users/hughesn/Microscopy Images/Effector images/2018-12-21"


# folders = {}

# for f in [folder1, folder2, folder3]:
#     czi_files = glob('{0}/*.czi'.format(f))
#     folders[f] = czi_files


def get_lif_images(img_name):
    reader = read_lif.Reader(img_name)
    series = reader.getSeries()
    imgs = []
    for s in series:
        chosen = s
        image = chosen.getFrame()
        img = np.max(image, axis=2)
        p2, p98 = np.percentile(img, (10, 99))
        img_rescale = exposure.rescale_intensity(img, in_range=(p2, p98))
        img_rescale = exposure.equalize_adapthist(img_rescale)
        imgs.append(img)
    return imgs


def mass_lif_conv(folder, outdir):
    for f in glob("{0}/*.lif".format(folder)):
        path = "{0}/{1}/".format(outdir, basename(f))
        if not os.path.exists(path):
            os.makedirs(path)
        images = get_lif_images(f)
        for idx, i in enumerate(images):
            imsave(path+str(idx)+'.png', i)

# folder1 = "/Users/hughesn/Microscopy Images/Effector images/2018-12-06" # folder2 = "/Users/hughesn/Microscopy Images/Effector images/2018-12-20" # folder3 = "/Users/hughesn/Microscopy Images/Effector images/2018-12-21" # folders = {} # for f in [folder1, folder2, folder3]: #     czi_files = glob('{0}/*.czi'.format(f)) #     folders[f] = czi_files