#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 28 2020

Created the __init__.py file.

@author: Alexander Hermann
"""

import argparse
import glob
import os
import re
import sys
import time
from .TiffReader import *

__IMG_KERNEL_SIZE_X = 5
__IMG_KERNEL_SIZE_Y = 5
__IMG_KERNEL_SIZE_Z = 5

def str2bool(v):
    if isinstance(v, bool):
       return v
    if v.lower() in ('yes', 'true', 'True', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'False', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.')

def main():
    try:
        # Create an argument parser
        parser = argparse.ArgumentParser(description="Script that reads a sequence of .tif files and outputs .csv file of voxel data to user specified directory")
        parser.add_argument('sFile', metavar='sFile', type=str, nargs='+', help='the source file of the .tif image sequence')
        parser.add_argument('-n', metavar='imgNum', type=int, default=None, help='number of .tif images')
        parser.add_argument('-r', metavar='resolution', type=float, default=1.0, help='voxel resolution in the .tif images')
        parser.add_argument('-d', metavar='dFile', type=str, default=None, help='the destination directory where the output should go to')
        parser.add_argument('-p', metavar='pooling', type=str2bool, default=False, help='optionally activate 2D pooling on the input images')
          
        args = parser.parse_args()
        
        # Source file directory
        sFile = args.sFile[0]
        
        # Get the number of .tif images
        if args.n is None:
            imgNum = len(glob.glob1(sFile,"*.tif"))
            if imgNum == 0:
                raise Exception("The number of .tif files in user specified directory is 0. Aborting process.")
        else:
            imgNum = args.n
        
        # Resolution
        resolution = args.r
        
        # If no destination file was passed, then assume we output in the same directory
        if args.d is None:
            dFile = sFile#os.getcwd()
        else:
            dFile = args.d  
        
        # List of .tif files in source direcotry
        files = glob.glob1(sFile,"*.tif")
        files.sort(key=lambda f: int(re.sub('\D', '', f)))
        
        # Instantiate the TiffReader class
        tr = TiffReader(sFile, files, dFile, imgNum, resolution)
        
        # Define optionally a dictionary for max/min pooling to reduce dimensions
        pooling_img   = {"kernel": (__IMG_KERNEL_SIZE_X, __IMG_KERNEL_SIZE_Y), "method": "max", "pad": False}
        pooling_img_z = {"kernel": (1, __IMG_KERNEL_SIZE_Z), "method": "max", "pad": False}
        
        # Read the images and get voxel coordinates
        print("Reading the input files ...", end =" ")
        
        tic = time.perf_counter()
        if args.p == True:
            tr.readImages(pooling_img, pooling_img_z)
        else:
            tr.readImages()
        toc = time.perf_counter()
        
        print(f"done. Time elapsed: {toc - tic:0.4f} seconds.")
            
        # Write the voxelized results to .csv output file
        print("Writing to output file ...", end =" ")
        
        out = "voxelization.csv"
        
        tic = time.perf_counter()
        tr.write_csv(out)
        toc = time.perf_counter()
        
        print(f"done. Time elapsed: {toc - tic:0.4f} seconds.")
        
        
    except:
        raise
        
    