from array import array

from  java.awt import EventQueue

from icy.main import Icy
from icy.image import IcyBufferedImage
from icy.sequence import Sequence, SequenceUtil
from icy.type import DataType

import plugins.adufour.ezplug as ezplug

class MyPythonPlugin(ezplug.EzPlug):
	def __init__(self):
		ezplug.EzPlug.__init__(self)
		self.inputSelector = ezplug.EzVarSequence("Input")
		self.thresholdSelector = ezplug.EzVarDouble("Threshold value")

	def getName(self):
		return "Python Thresholder"

	def initialize(self):
		self.addEzComponent(self.inputSelector)
		self.addEzComponent(self.thresholdSelector)

	def execute(self):
		sequence = self.inputSelector.getValue()
		m = self.thresholdSelector.getValue()

		# exit immediately if there is no input sequence
		if sequence == None:
			return

		# convert the data to doubles so that the comparison to the threshold
		# works everytime (it would fail with bytes because of sign issues)
		if sequence.getDataType_() == DataType.DOUBLE:
			doubleSeq = sequence
		else:
			doubleSeq = SequenceUtil.convertToType(sequence, DataType.DOUBLE, False)

		# retrieve the data
		data = doubleSeq.getDataCopyXYAsDouble(0,0,0)

		for i, p in enumerate(data):
			if p<m:
				data[i] = 0.

		im2 = IcyBufferedImage(sequence.getSizeX(), sequence.getSizeY(), data)
		seq = Sequence(im2)
		Icy.addSequence(seq)

	def clean(self):
		return

# create the plugin in the UI thread
def run():
	plugin = MyPythonPlugin()
	plugin.compute()

EventQueue.invokeAndWait(run)
