import ij
from ij.io import Opener
from ijutils import *
from ch.psi.pshell.imaging.Overlays import *
from ch.psi.pshell.imaging.Utils import *
import ch.psi.pshell.imaging.Pen as Pen
import java.awt.Rectangle as Rectangle
import ch.psi.pshell.imaging.Data as Data


def integrate(ips, as_float=True):    
    aux = None
    for i in range(len(ips)):
        if i==0:        
            img_type = "float" if as_float else "short"
            aux = new_image(ips[i].width, ips[i].height, image_type=img_type, title = "sum", fill_color = None)
        op_image(aux, ips[i], "add", float_result=as_float, in_place=True)    
    return aux

def average (ips, roi=None, as_float=True):   
    aux = integrate(ips, as_float)     
    op_const(aux, "divide", float(len(ips)), in_place=True)    
    return aux

def get_image(source, roi=None, wait_next=False):
    if wait_next:
        source.waitNext(-1)
    ret = load_image(Utils.grayscale(source.output, Rectangle(roi[0], roi[1], roi[2], roi[3]) if (roi is not None) else None))
    return ret
    
def grab_frames(source, samples, roi=None, wait_next=False, sleep=0):
    frames = []            
    for i in range(samples):
        if sleep>0:
            time.sleep(sleep)
        aux = get_image(source, roi, wait_next)        
        frames.append(aux)        
    return frames
    
def average_frames(source, samples=1, roi=None, wait_next=False, sleep=0, as_float=True):
    return average(grab_frames(source, samples, roi, wait_next, sleep), as_float)

def integrate_frames(source, samples=1, roi=None, wait_next=False, sleep=0, as_float=True):
    return integrate(grab_frames(source, samples, roi, wait_next, sleep), as_float)
    

def get_image_array(ip):
    if type(ip.getProcessor()) == ij.process.FloatProcessor:
        return ip.getProcessor().getFloatArray()
    else:
        return ip.getProcessor().getIntArray()

def open_image(file_name):
    file_name = get_context().setup.expandPath(file_name)
    return Opener().openTiff(file_name, 1)

        
ret = grab_frames(image, 10, sleep=0.1)
av = average(ret, None, True)
print type(av.getProcessor())
#db=av.getBufferedImage().getData().getDataBuffer()
data = get_image_array(av)
plot(data)

save_image(av, "{images}/float.tif","tiff")
av = average(ret, None, False)
save_image(av, "{images}/int.tif","tiff")
