local Y={}Y.Version=script.Parent.Version.Value Y.Services={}Y.Util=script.Parent.Util local s=Instance.new("\070\111\108\100\101\114")s.Name="\083\101\114\118\105\099\101\115"local Z=require(Y.Util.Promise)local x=require(Y.Util.Thread)local b=require(Y.Util.Signal)local J=require(Y.Util.Loader)local S=require(Y.Util.Ser)local c=require(Y.Util.Remote.RemoteSignal)local O=require(Y.Util.Remote.RemoteProperty)local Q=require(Y.Util.TableUtil)local d=false local p=false local f=Instance.new("\066\105\110\100\097\098\108\101\069\118\101\110\116")local function L(Y)local s=Instance.new("\070\111\108\100\101\114")s.Name=Y return s end local function E(Y,s)local Z=Y:FindFirstChild(s)if not Z then Z=Instance.new("\070\111\108\100\101\114")Z.Name=s Z.Parent=Y end return Z end local function m(Y,Z,x)if x then Z.Parent=E(Y._knit_rep_folder,x)elseif Z:IsA("\082\101\109\111\116\101\070\117\110\099\116\105\111\110")then Z.Parent=E(Y._knit_rep_folder,"\082\070")elseif Z:IsA("\082\101\109\111\116\101\069\118\101\110\116")then Z.Parent=E(Y._knit_rep_folder,"\082\069")elseif Z:IsA("\086\097\108\117\101\066\097\115\101")then Z.Parent=E(Y._knit_rep_folder,"\082\080")else error("\073\110\118\097\108\105\100 \114\101\112 \111\098\106\101\099\116\058 "..Z.ClassName)end if not Y._knit_rep_folder.Parent then Y._knit_rep_folder.Parent=s end end function Y.IsService(Y)return type(Y)=="\116\097\098\108\101"and Y._knit_is_service==true end function Y.CreateService(s)assert(type(s)=="\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(s))assert(type(s.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(s.Name))assert(#s.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(Y.Services[s.Name]==nil,"\083\101\114\118\105\099\101 \""..(s.Name.."\" \097\108\114\101\097\100\121 \101\120\105\115\116\115"))Q.Extend(s,{_knit_is_service=true,_knit_rf={};_knit_re={},_knit_rp={},_knit_rep_folder=L(s.Name)})if type(s.Client)~="\116\097\098\108\101"then s.Client={Server=s}else if s.Client.Server~=s then s.Client.Server=s end end Y.Services[s.Name]=s return s end function Y.AddServices(Y)return J.LoadChildren(Y)end function Y.AddServicesDeep(Y)return J.LoadDescendants(Y)end function Y.BindRemoteEvent(Y,s,Z)assert(Y._knit_re[s]==nil,"\082\101\109\111\116\101\069\118\101\110\116 \""..(s.."\" \097\108\114\101\097\100\121 \101\120\105\115\116\115"))local x=Z._remote x.Name=s Y._knit_re[s]=x m(Y,x)end function Y.BindRemoteFunction(Y,s,Z)assert(Y._knit_rf[s]==nil,"\082\101\109\111\116\101\070\117\110\099\116\105\111\110 \""..(s.."\" \097\108\114\101\097\100\121 \101\120\105\115\116\115"))local x=Instance.new("\082\101\109\111\116\101\070\117\110\099\116\105\111\110")x.Name=s Y._knit_rf[s]=x m(Y,x)function x.OnServerInvoke(...)return S.SerializeArgsAndUnpack(Z(Y.Client,S.DeserializeArgsAndUnpack(...)))end end function Y.BindRemoteProperty(Y,s,Z)assert(Y._knit_rp[s]==nil,"\082\101\109\111\116\101\080\114\111\112\101\114\116\121 \""..(s.."\" \097\108\114\101\097\100\121 \101\120\105\115\116\115"))Z._object.Name=s Y._knit_rp[s]=Z m(Y,Z._object,"\082\080")end function Y.Start()if d then return Z.Reject("\075\110\105\116 \097\108\114\101\097\100\121 \115\116\097\114\116\101\100")end d=true local J=Y.Services return(Z.new(function(s)for s,Z in pairs(J)do for s,x in pairs(Z.Client)do if type(x)=="\102\117\110\099\116\105\111\110"then Y.BindRemoteFunction(Z,s,x)elseif c.Is(x)then Y.BindRemoteEvent(Z,s,x)elseif O.Is(x)then Y.BindRemoteProperty(Z,s,x)elseif b.Is(x)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"..(Z.Name..("\046\067\108\105\101\110\116\046"..(s.."\093"))))end end end local x={}for Y,s in pairs(J)do if type(s.KnitInit)=="\102\117\110\099\116\105\111\110"then table.insert(x,Z.new(function(Y)s:KnitInit()Y()end))end end s(Z.All(x))end)):Then(function()for Y,s in pairs(J)do if type(s.KnitStart)=="\102\117\110\099\116\105\111\110"then x.SpawnNow(s.KnitStart,s)end end p=true f:Fire()x.Spawn(function()f:Destroy()end)s.Parent=script.Parent end)end function Y.OnStart()if p then return Z.Resolve()else return Z.new(function(Y)if p then Y()return end f.Event:Wait()Y()end)end end return Y


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")
	TableUtil.Extend(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.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.new(function(resolve)
			if startedComplete then
				resolve()
				return
			end
			onStartedComplete.Event:Wait()
			resolve()
		end)
	end
end

return KnitServer
