local module = {}

function position(motor,phase,phases,target,origin)
	motor.C0 = origin
	local alpha = (phase)/(phases-1)
	motor.C1 = CFrame.new():Lerp(target,alpha)
end

function module.new(this,lever,context)
	this.motor = _G.GetInstance(lever,"Motor")
	this.phase = _G.GetInstance(lever,"Phase")
	this.phases = _G.GetInstance(lever,"Phases")
	this.hold = _G.GetInstance(lever,"Hold")
	this.click = _G.GetInstance(this.hold,"ClickDetector")
	this.target = lever:GetAttribute("Target") or error("Needs target attribute.")
	this.origin = lever:GetAttribute("Origin") or error("Needs target attribute.")
	if _G.IsServer then 
		module.update(this,lever,context)
		this.click.MouseClick:Connect(function()
			if this.phase.Value == this.phases.Value - 1 then 
				this.phase.Value = 0
			else
				this.phase.Value += 1
			end
			print(this.phase.Value)
			module.update(this,lever,context)
			context.connected("ConnectorData",nil,lever.PrimaryPart,function(object)
				print("firing",this.phase.Value)
				context.message(object,nil,this.phase.Value/(this.phases.Value-1))
			end)
		end)
	end
end

function module.update(this,lever,context)
	if _G.IsServer then
		position(this.motor,this.phase.Value,this.phases.Value,this.target,this.origin)
	end
end

module.manifest = {
	"Lever"
}

return module