# MIT License
# Copyright (c) 2017 dcolam
from __future__ import with_statement, division
import sys, time, os, traceback, random, time, ConfigParser, csv, math, fnmatch, locale
from ij import IJ
from org.scijava.util import ColorRGB
from ij.gui import GenericDialog, WaitForUserDialog
from ij.process import ImageProcessor
from ClusterAnalysisModuls.config import config


#@File(label = "Select an input folder with the images to analyze", value=expath, required=true, style="directory", persist=true) expath
#@String (label="Name of Experiment", value="Example") expName
#@Boolean(label="Headless?", value=True) headless
#@Boolean(label="Set Measurements", value=True) measure
#@String (label="What visualisation color is preferred?", choices= {"Black and White", "Red", "Over/Under"}) c
#@ColorRGB (label="Color of Selections?", value="magenta") colSel
#@ColorRGB (label="Color of found Particles?", value="green") colParticles
#@ColorRGB (label="Color of Colocalisation Selection?", value="red") colColoc

def find(name, path):
    result = []
    for root, dirs, files in os.walk(path):
        # print root
        if name in files:
            result.append(os.path.join(root, name))
    return result

def gc():
    print "Free Memory ", IJ.freeMemory()
    IJ.run("Console", "")
    return IJ.currentMemory()

def formatTime(start):
    t = time.time() - start
    u = " seconds"
    if t > 60:
        t /= 60
        u = " minutes"
        if t > 60:
            t /= 60
            u = " hours"
            if t > 24:
                t /= 24
                u = " days"
    return str(round(t, 2)) + u


####### Start of the script

dir_path = os.path.realpath('__file__')
dir_path = os.path.dirname(os.path.realpath('__file__'))
files = find("Cluster_Analysis_BETA_v3.py", dir_path)
for f in files:
    dir_path = os.path.dirname(f)
print dir_path
luts = {"Black and White": ImageProcessor.BLACK_AND_WHITE_LUT, "Red": ImageProcessor.RED_LUT, "Over/Under": ImageProcessor.OVER_UNDER_LUT}

if __name__ in ['__builtin__', '__main__']:
    
    import ClusterAnalysisModuls.globalVars
    IJ.run("Close All", "")
    if headless:
        colSel = ColorRGB("White"),
        colParticles = ColorRGB("White"),
        colColoc = ColorRGB("White")

    # Set Measurements
    if measure:
        IJ.run("Set Measurements...", "")
    else:
        IJ.run("Set Measurements...", "area mean standard min integrated redirect=None decimal=3")
    expath2 = expath.getAbsolutePath()

    # Read config-file
    ClusterAnalysisModuls.globalVars.dir_path = dir_path
    ClusterAnalysisModuls.globalVars.expName = expName
    ClusterAnalysisModuls.globalVars.expath = expath
    ClusterAnalysisModuls.globalVars.expath2 = expath2
    ClusterAnalysisModuls.globalVars.headless = headless
    ClusterAnalysisModuls.globalVars.luts = luts
    ClusterAnalysisModuls.globalVars.c = c
    ClusterAnalysisModuls.globalVars.colSel = colSel
    ClusterAnalysisModuls.globalVars.colParticles = colParticles
    ClusterAnalysisModuls.globalVars.colColoc = colColoc
    
    cp = config()
    cp.readIni()
    
    ClusterAnalysisModuls.globalVars.cp = cp
    
    from ClusterAnalysisModuls.GUITools import Dialoger, testParameters
    from ClusterAnalysisModuls.ImageTools import Image
    #from ClusterAnalysisModuls.dbInterface import db_interface
    
    IJ.redirectErrorMessages(True)
    memory = gc()
    IJ.setDebugMode(False)
    IJ.resetEscape()
    # Gather Parameters for the analysis
    t = testParameters()
    d, s, db = t.startScript()
    errors = []
    start = time.time()

    # Loop over images
    for index, i in enumerate(d.filenames):
        if not IJ.escapePressed():
            try:
                print "Analysing image: ", os.path.split(i)[1]
                progress = round(float(index+1)/float(len(d.filenames)), 3)
                print "Progress: %s of %s images (%s percent), Time: %s" %(index + 1, len(d.filenames), progress*100, formatTime(start))
                print "x"*int((progress*100))
                #First Image gets analyzed
                if not index:
                    l = Image(i, d, s, False, first=True)
                    db_path = d.output_path_dict["output_table_path"]
                    # initiate database after first image
                    #db = db_interface(db_path, l)
                    db.extractData(l, True)
                    if not headless:
                        # write new parameters into new config-file
                        cp.writeIni()
                else:
                    l = Image(i, d, s, False)
                    # store information into the database
                    db.extractData(l)
                if not index % 10:
                    gc()
            # Try-catch statement so that analysis is not interrupted
            except:
                exc_type, exc_value, exc_traceback = sys.exc_info()
                lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
                print ''.join('!! ' + line for line in lines)
                print "Analysis of image %s failed" % os.path.split(i)[1]
                errors.append(i)
                IJ.run("Close All")
                l = None
            finally:
                try:
                    if not db:
                        sys.exit("Inititation of database failed!\nCheck Troubleshooting!")
                        break
                except:    
                    sys.exit("Inititation of database failed! Check Troubleshooting!")
    db.writeCSV()
    db.closeConn()

    if not headless:
        WaitForUserDialog(
            "Analysis is done! \n Number of images analyzed: %s \n Running time: %s \n Number of failed images: %s"
            % (len(d.filenames),
               formatTime(start),
               len(errors))).show()
    print "Number of images analyzed: ", len(d.filenames)
    print 'It took', formatTime(start), 'seconds.'

    for e in errors:
        print "Failed Images: ", e

    if headless:
        if len(errors) == len(d.filenames):
            sys.exit(-1)
        else:
            sys.exit(0)