local c={}c.Version=script.Parent.Version.Value c.Services={}c.Util=script.Parent.Util local e=Instance.new("\070\111\108\100\101\114")e.Name="\083\101\114\118\105\099\101\115"local b=require(c.Util.Promise)local W=require(c.Util.Thread)local i=require(c.Util.Signal)local Q=require(c.Util.Loader)local n=require(c.Util.Ser)local P=require(c.Util.Remote.RemoteSignal)local u=require(c.Util.Remote.RemoteProperty)local s=require(c.Util.TableUtil)local j=false local w=false local X=Instance.new("\066\105\110\100\097\098\108\101\069\118\101\110\116")local function O(c)local e=Instance.new("\070\111\108\100\101\114")e.Name=c return e end local function l(c,e)local b=c:FindFirstChild(e)if not b then b=Instance.new("\070\111\108\100\101\114")b.Name=e b.Parent=c end return b end local function I(c,b,W)if W then b.Parent=l(c._knit_rep_folder,W)elseif b:IsA("\082\101\109\111\116\101\070\117\110\099\116\105\111\110")then b.Parent=l(c._knit_rep_folder,"\082\070")elseif b:IsA("\082\101\109\111\116\101\069\118\101\110\116")then b.Parent=l(c._knit_rep_folder,"\082\069")elseif b:IsA("\086\097\108\117\101\066\097\115\101")then b.Parent=l(c._knit_rep_folder,"\082\080")else error("\073\110\118\097\108\105\100 \114\101\112 \111\098\106\101\099\116\058 "..b.ClassName)end if not c._knit_rep_folder.Parent then c._knit_rep_folder.Parent=e end end function c.IsService(c)return type(c)=="\116\097\098\108\101"and c._knit_is_service==true end function c.CreateService(e)assert(type(e)=="\116\097\098\108\101","\083\101\114\118\105\099\101 \109\117\115\116 \098\101 \097 \116\097\098\108\101\059 \103\111\116 "..type(e))assert(type(e.Name)=="\115\116\114\105\110\103","\083\101\114\118\105\099\101\046\078\097\109\101 \109\117\115\116 \098\101 \097 \115\116\114\105\110\103\059 \103\111\116 "..type(e.Name))assert(#e.Name>0,"\083\101\114\118\105\099\101\046\078\097\109\101 \109\117\115\116 \098\101 \097 \110\111\110-\101\109\112\116\121 \115\116\114\105\110\103")assert(c.Services[e.Name]==nil,"\083\101\114\118\105\099\101 \""..(e.Name.."\" \097\108\114\101\097\100\121 \101\120\105\115\116\115"))e=s.Assign(e,{_knit_is_service=true,_knit_rf={},_knit_re={};_knit_rp={},_knit_rep_folder=O(e.Name)})if type(e.Client)~="\116\097\098\108\101"then e.Client={Server=e}else if e.Client.Server~=e then e.Client.Server=e end end c.Services[e.Name]=e return e end function c.AddServices(c)return Q.LoadChildren(c)end function c.AddServicesDeep(c)return Q.LoadDescendants(c)end function c.GetService(e)assert(type(e)=="\115\116\114\105\110\103","\083\101\114\118\105\099\101\078\097\109\101 \109\117\115\116 \098\101 \097 \115\116\114\105\110\103\059 \103\111\116 "..type(e))return assert(c.Services[e],"\067\111\117\108\100 \110\111\116 \102\105\110\100 \115\101\114\118\105\099\101 \""..(e.."\""))end function c.BindRemoteEvent(c,e,b)assert(c._knit_re[e]==nil,"\082\101\109\111\116\101\069\118\101\110\116 \""..(e.."\" \097\108\114\101\097\100\121 \101\120\105\115\116\115"))local W=b._remote W.Name=e c._knit_re[e]=W I(c,W)end function c.BindRemoteFunction(c,e,b)assert(c._knit_rf[e]==nil,"\082\101\109\111\116\101\070\117\110\099\116\105\111\110 \""..(e.."\" \097\108\114\101\097\100\121 \101\120\105\115\116\115"))local W=Instance.new("\082\101\109\111\116\101\070\117\110\099\116\105\111\110")W.Name=e c._knit_rf[e]=W I(c,W)function W.OnServerInvoke(...)return n.SerializeArgsAndUnpack(b(c.Client,n.DeserializeArgsAndUnpack(...)))end end function c.BindRemoteProperty(c,e,b)assert(c._knit_rp[e]==nil,"\082\101\109\111\116\101\080\114\111\112\101\114\116\121 \""..(e.."\" \097\108\114\101\097\100\121 \101\120\105\115\116\115"))b._object.Name=e c._knit_rp[e]=b I(c,b._object,"\082\080")end function c.Start()if j then return b.Reject("\075\110\105\116 \097\108\114\101\097\100\121 \115\116\097\114\116\101\100")end j=true local Q=c.Services return(b.new(function(e)for e,b in pairs(Q)do for e,W in pairs(b.Client)do if type(W)=="\102\117\110\099\116\105\111\110"then c.BindRemoteFunction(b,e,W)elseif P.Is(W)then c.BindRemoteEvent(b,e,W)elseif u.Is(W)then c.BindRemoteProperty(b,e,W)elseif i.Is(W)then warn("\070\111\117\110\100 \083\105\103\110\097\108 \105\110\115\116\101\097\100 \111\102 \082\101\109\111\116\101\083\105\103\110\097\108 \040\075\110\105\116\046\085\116\105\108\046\082\101\109\111\116\101\083\105\103\110\097\108\041\046 \080\108\101\097\115\101 \099\104\097\110\103\101 \116\111 \082\101\109\111\116\101\083\105\103\110\097\108\046 \091"..(b.Name..("\046\067\108\105\101\110\116\046"..(e.."\093"))))end end end local W={}for c,e in pairs(Q)do if type(e.KnitInit)=="\102\117\110\099\116\105\111\110"then table.insert(W,b.new(function(c)e:KnitInit()c()end))end end e(b.All(W))end)):Then(function()for c,e in pairs(Q)do if type(e.KnitStart)=="\102\117\110\099\116\105\111\110"then W.SpawnNow(e.KnitStart,e)end end w=true X:Fire()W.Spawn(function()X:Destroy()end)e.Parent=script.Parent end)end function c.OnStart()if w then return b.Resolve()else return b.FromEvent(X.Event)end end return c



local KnitServer = {}

KnitServer.Version = script.Parent.Version.Value
KnitServer.Services = {}
KnitServer.Util = script.Parent.Util


local knitRepServiceFolder = Instance.new("Folder")
knitRepServiceFolder.Name = "Services"

local Promise = require(KnitServer.Util.Promise)
local Thread = require(KnitServer.Util.Thread)
local Signal = require(KnitServer.Util.Signal)
local Loader = require(KnitServer.Util.Loader)
local Ser = require(KnitServer.Util.Ser)
local RemoteSignal = require(KnitServer.Util.Remote.RemoteSignal)
local RemoteProperty = require(KnitServer.Util.Remote.RemoteProperty)
local TableUtil = require(KnitServer.Util.TableUtil)

local started = false
local startedComplete = false
local onStartedComplete = Instance.new("BindableEvent")


local function CreateRepFolder(serviceName)
	local folder = Instance.new("Folder")
	folder.Name = serviceName
	return folder
end


local function GetFolderOrCreate(parent, name)
	local f = parent:FindFirstChild(name)
	if (not f) then
		f = Instance.new("Folder")
		f.Name = name
		f.Parent = parent
	end
	return f
end


local function AddToRepFolder(service, remoteObj, folderOverride)
	if (folderOverride) then
		remoteObj.Parent = GetFolderOrCreate(service._knit_rep_folder, folderOverride)
	elseif (remoteObj:IsA("RemoteFunction")) then
		remoteObj.Parent = GetFolderOrCreate(service._knit_rep_folder, "RF")
	elseif (remoteObj:IsA("RemoteEvent")) then
		remoteObj.Parent = GetFolderOrCreate(service._knit_rep_folder, "RE")
	elseif (remoteObj:IsA("ValueBase")) then
		remoteObj.Parent = GetFolderOrCreate(service._knit_rep_folder, "RP")
	else
		error("Invalid rep object: " .. remoteObj.ClassName)
	end
	if (not service._knit_rep_folder.Parent) then
		service._knit_rep_folder.Parent = knitRepServiceFolder
	end
end


function KnitServer.IsService(object)
	return type(object) == "table" and object._knit_is_service == true
end


function KnitServer.CreateService(service)
	assert(type(service) == "table", "Service must be a table; got " .. type(service))
	assert(type(service.Name) == "string", "Service.Name must be a string; got " .. type(service.Name))
	assert(#service.Name > 0, "Service.Name must be a non-empty string")
	assert(KnitServer.Services[service.Name] == nil, "Service \"" .. service.Name .. "\" already exists")
	service = TableUtil.Assign(service, {
		_knit_is_service = true;
		_knit_rf = {};
		_knit_re = {};
		_knit_rp = {};
		_knit_rep_folder = CreateRepFolder(service.Name);
	})
	if (type(service.Client) ~= "table") then
		service.Client = {Server = service}
	else
		if (service.Client.Server ~= service) then
			service.Client.Server = service
		end
	end
	KnitServer.Services[service.Name] = service
	return service
end


function KnitServer.AddServices(folder)
	return Loader.LoadChildren(folder)
end


function KnitServer.AddServicesDeep(folder)
	return Loader.LoadDescendants(folder)
end


function KnitServer.GetService(serviceName)
	assert(type(serviceName) == "string", "ServiceName must be a string; got " .. type(serviceName))
	return assert(KnitServer.Services[serviceName], "Could not find service \"" .. serviceName .. "\"")
end


function KnitServer.BindRemoteEvent(service, eventName, remoteEvent)
	assert(service._knit_re[eventName] == nil, "RemoteEvent \"" .. eventName .. "\" already exists")
	local re = remoteEvent._remote
	re.Name = eventName
	service._knit_re[eventName] = re
	AddToRepFolder(service, re)
end


function KnitServer.BindRemoteFunction(service, funcName, func)
	assert(service._knit_rf[funcName] == nil, "RemoteFunction \"" .. funcName .. "\" already exists")
	local rf = Instance.new("RemoteFunction")
	rf.Name = funcName
	service._knit_rf[funcName] = rf
	AddToRepFolder(service, rf)
	function rf.OnServerInvoke(...)
		return Ser.SerializeArgsAndUnpack(func(service.Client, Ser.DeserializeArgsAndUnpack(...)))
	end
end


function KnitServer.BindRemoteProperty(service, propName, prop)
	assert(service._knit_rp[propName] == nil, "RemoteProperty \"" .. propName .. "\" already exists")
	prop._object.Name = propName
	service._knit_rp[propName] = prop
	AddToRepFolder(service, prop._object, "RP")
end


function KnitServer.Start()

	if (started) then
		return Promise.Reject("Knit already started")
	end

	started = true

	local services = KnitServer.Services

	return Promise.new(function(resolve)

		-- Bind remotes:
		for _,service in pairs(services) do
			for k,v in pairs(service.Client) do
				if (type(v) == "function") then
					KnitServer.BindRemoteFunction(service, k, v)
				elseif (RemoteSignal.Is(v)) then
					KnitServer.BindRemoteEvent(service, k, v)
				elseif (RemoteProperty.Is(v)) then
					KnitServer.BindRemoteProperty(service, k, v)
				elseif (Signal.Is(v)) then
					warn("Found Signal instead of RemoteSignal (Knit.Util.RemoteSignal). Please change to RemoteSignal. [" .. service.Name .. ".Client." .. k .. "]")
				end
			end
		end

		-- Init:
		local promisesInitServices = {}
		for _,service in pairs(services) do
			if (type(service.KnitInit) == "function") then
				table.insert(promisesInitServices, Promise.new(function(r)
					service:KnitInit()
					r()
				end))
			end
		end

		resolve(Promise.All(promisesInitServices))

	end):Then(function()

		-- Start:
		for _,service in pairs(services) do
			if (type(service.KnitStart) == "function") then
				Thread.SpawnNow(service.KnitStart, service)
			end
		end

		startedComplete = true
		onStartedComplete:Fire()

		Thread.Spawn(function()
			onStartedComplete:Destroy()
		end)

		-- Expose service remotes to everyone:
		knitRepServiceFolder.Parent = script.Parent

	end)

end


function KnitServer.OnStart()
	if (startedComplete) then
		return Promise.Resolve()
	else
		return Promise.FromEvent(onStartedComplete.Event)
	end
end


return KnitServer
