local module = {}

local programModule = require(_G.Modules.ProgramModule)

function module.new(this,computer,context)
	this.value = _G.GetInstance(computer,"Program")
	this.led = _G.GetInstance(computer,"LED")
	this.program = programModule.open_program(this.value,nil)
	this.program:load()
	this.inputs = {}
	this.output = function(pin,name,value)
		context.connected("ConnectorData","ConnectorEnd",computer[pin],function(object)
			context.message(object,name,value)
		end)
	end
	this.input = function(name)
		return this.inputs[name]
	end
	this.control = function(name)
		return context.controls[name]
	end
	this.message = function(title,value)
		if context.queue(this,"notification",3) then _G.Events.Notification:Fire(title,value) end
	end
	this.led.Color = Color3.fromRGB(255,255,255)
	return this
end

local begin = tick()
module.run = _G.Protect(function(this,computer,context)
	if not this.program then this.led.Color = Color3.fromRGB(255,0,0) return true end
	this.led.Color = Color3.fromRGB(0,255,0)
	this.program.variables = this.variables or {}
	this.program:run(this)
	context.replicate(this,computer,module,this.program.variables)
	return true
end)

function module.remove(this,computer,context)
	
end

module.replication_delta = 0.25
function module.replicate(this,computer,context,variables)
	this.variables = variables
end

module.messages = {
	default = function(this,object,context,value)
		local pin = object.Name
		this.inputs[pin] = value
	end
}

module.manifest = {
	"Microcontroller"
}

return module
