import papermill as pm
from subprocess import Popen
import os

root_path = ''
with open('../paths.config', 'r') as f:
    root_path = f.read()
    root_path = root_path.strip()
    f.close()

os.chdir(os.path.join('cancer_img', 'tissue_masking'))

def run_with_pm(input_file: str, id: str) -> None:
    output_file = os.path.join(id, f'{id}_output.ipynb')
    pm.execute_notebook( os.path.join('tissue_masking.ipynb'), output_file, parameters = dict(file = rf'{input_file}'))

    conversion_cmd = f"python3 -m jupyter nbconvert --TemplateExporter.exclude_input=True --to html {output_file}"

    process = Popen(conversion_cmd, shell=True)

    process.wait()

    move_to_templates = f"mv {output_file.split('.')[0] + '.html'} templates"

    process = Popen(move_to_templates, shell=True)

    process.wait()

    return True

def generate_output_images(input_file: str, id: str) -> None:
    ###Tissue Masking###
    import math, cv2
    from skimage import morphology
    import slideio
    import matplotlib.pyplot as plt

    slide = slideio.open_slide(input_file, "SVS")
    scene1 = slide.get_scene(0)
    image1 = scene1.read_block((0,0,1000,1000))
    scene2  = slide.get_scene(0)
    scene2.name, scene2.rect, scene2.num_channels, scene2.resolution
    image2 = scene2.read_block(size=(500,0))

    # an example function using intensity thresholding and morphological operations to obtain tissue regions
    def simple_get_mask(rgb):
        gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
        _, mask = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU) # threshold using the OTSU method
        mask = morphology.remove_small_objects(mask == 0, min_size=100, connectivity=2)
        mask = morphology.remove_small_holes(mask, area_threshold=100)
        mask = morphology.binary_dilation(mask, morphology.disk(5))
        return mask

    # plot thumbnail (left) with its tissue mask (right)
    image = simple_get_mask(image2)
    fig, axarr = plt.subplots(1,3, figsize=(20,20))
    axarr[0].imshow(image1, cmap='gray')
    axarr[1].imshow(image2, cmap='gray')
    axarr[2].imshow(image, cmap='gray')
    axarr[2].set_title("tissue mask")
    os.chdir(root_path)
    print(f'outputting the file with id:{id}')
    plt.savefig(os.path.join('static', f'{id}_output.png'))

    return True
