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


###############################################################################
# ROI Integration
###############################################################################

def integrate_roi(source, x,y, w, h):
    if source.data is None:
        source.update()
    roi = source.data.getRoi(Rectangle(x,y, w, h))
    return roi.integrate(False)



class RoiIntensity(ReadonlyRegisterBase):
    def __init__(self, name, source, x,y, w, h):
        ReadonlyRegisterBase.__init__(self, name)
        self.source=source
        self.roi = x,y, w, h
        
    def doRead(self):
        x,y, w, h = self.roi
        return integrate_roi(self.source, x,y, w, h)

###############################################################################
# Frame integration
###############################################################################

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_ips(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_ips(grab_frames(source, samples, roi, wait_next, sleep), as_float)
    

