local function q(q)if q.SyncToAudio then assert(q.SyncToAudio.Audio~=nil,"\070\097\105\108\101\100 \116\111 \099\114\101\097\116\101 \099\111\110\102\105\103 \124 \101\120\112\101\099\116\101\100 \097\110 \065\117\100\105\111 \102\111\114 \083\121\110\099\084\111\065\117\100\105\111\044 \098\117\116 \114\101\099\101\105\118\101\100 \110\105\108")assert(q.SyncToAudio.StartAtAudioTime~=nil,"\070\097\105\108\101\100 \116\111 \099\114\101\097\116\101 \099\111\110\102\105\103 \124 \101\120\112\101\099\116\101\100 \097 \083\116\097\114\116\065\116\065\117\100\105\111\084\105\109\101 \102\111\114 \083\121\110\099\084\111\065\117\100\105\111\044 \098\117\116 \114\101\099\101\105\118\101\100 \110\105\108")else assert(q.StartTime~=nil,"\070\097\105\108\101\100 \116\111 \099\114\101\097\116\101 \099\111\110\102\105\103 \124 \101\120\112\101\099\116\101\100 \099\111\110\102\105\103\046\083\116\097\114\116\084\105\109\101 \111\114 \099\111\110\102\105\103\046\083\121\110\099\084\111\065\117\100\105\111\044 \098\117\116 \114\101\099\101\105\118\101\100 \110\105\108")end assert(q.Adornee~=nil,"\073\110\118\097\108\105\100 \065\100\111\114\110\101\101 \124 \112\097\114\116 \101\120\112\101\099\116\101\100 \103\111\116 \110\105\108")assert(type(q.VideoId)=="\115\116\114\105\110\103","\073\110\118\097\108\105\100 \086\105\100\101\111\073\100 \124 \115\116\114\105\110\103 \101\120\112\101\099\116\101\100 \103\111\116 "..type(q.VideoId))if q.OnStart then assert(type(q.OnStart)=="\102\117\110\099\116\105\111\110","\073\110\118\097\108\105\100 \079\110\083\116\097\114\116 \124 \102\117\110\099\116\105\111\110 \101\120\112\101\099\116\101\100 \103\111\116 "..type(q.OnStart))end if q.OnEnd then assert(type(q.OnEnd)=="\102\117\110\099\116\105\111\110","\073\110\118\097\108\105\100 \079\110\069\110\100 \124 \102\117\110\099\116\105\111\110 \101\120\112\101\099\116\101\100 \103\111\116 "..type(q.OnEnd))end if q.Face then assert(typeof(q.Face)=="\069\110\117\109\073\116\101\109","\073\110\118\097\108\105\100 \070\097\099\101 \069\110\117\109 \124 \101\110\117\109 \101\120\112\101\099\116\101\100 \103\111\116 "..typeof(q.Face))end if q.Captions then local O=q.Captions.CaptionString assert(O~=nil and type(O)=="\115\116\114\105\110\103","\073\110\118\097\108\105\100 \067\097\112\116\105\111\110\083\116\114\105\110\103 \124 \115\116\114\105\110\103 \101\120\112\101\099\116\101\100 \103\111\116 "..type(O))end end local O={}O.__index=O O.Type="\086\105\100\101\111"O.task=task function O._constructVideo(O,q)O.SurfaceGui=Instance.new("\083\117\114\102\097\099\101\071\117\105")local V=Players.LocalPlayer:WaitForChild("\080\108\097\121\101\114\071\117\105")O.SurfaceGui.Adornee=O.Adornee O.SurfaceGui.Face=O.Face O.SurfaceGui.Name=O.Adornee.Name O.SurfaceGui.Parent=V if O.SurfaceGuiProperties then for q,V in pairs(O.SurfaceGuiProperties)do O.SurfaceGui[q]=V end end O.VideoFrame=Instance.new("\086\105\100\101\111\070\114\097\109\101")O.VideoFrame.Video=q O.VideoFrame.Size=UDim2.new(1,0,1,0)O.VideoFrame.Parent=O.SurfaceGui if O.Captions then O.VideoFrame:SetAttribute(enums.Attribute.Captions,O.Captions.CaptionString or"")O.CaptionsModule=CaptionsModule.new(O.VideoFrame)if O.CCButton then O.CCButton=O.CCButton:Clone()else O.CCButton=script.CCButton:Clone()end O.CCButton.Parent=O.SurfaceGui local q=O.CaptionsModule.CaptionLabel O.captionButtonConnection=O.CCButton.Activated:Connect(function()local V=q.Visible if V then O.CCButton.Image=ccOffIcon else O.CCButton.Image=ccIcon end q.Visible=not V end)end return O.VideoFrame end function O._calculateCurrentSoundIntensityRatio(O,q)local V=O.LoudestPlayback local d=q.volume O.LoudestPlayback=math.max(d,V)return d/O.LoudestPlayback end function O.new(V)q(V)local d=setmetatable({},O)d.OnStart=V.OnStart or function(q) end d.OnEnd=V.OnEnd or function(q) end d.CurrentSoundIntensityRatio=1 d.LoudestPlayback=1 d.IsCancelled=false d.SyncToAudio=V.SyncToAudio d.VideoId=V.VideoId d.Adornee=V.Adornee d.Face=V.Face or Enum.NormalId.Top d.TimeLength=V.TimeLength d.SurfaceGuiProperties=V.SurfaceGuiProperties d.Captions=V.Captions d.CaptionsModule=V.CaptionsModule d.StartTime=V.StartTime if d.SyncToAudio then d.StartTime=d.SyncToAudio.Audio.StartTime+d.SyncToAudio.StartAtAudioTime end return d end function O._attemptOnStart(q)if q.OnStart~=nil then SafeSpawn.new(function()q:OnStart()end)end end function O._attemptOnEnd(q)if q.OnEnd~=nil then SafeSpawn.new(function()q:OnEnd()end)end end function O.getSchemaProcessorTimePosition(O,q)return q.timePosition.Value end function O.getCurrentSoundTimePosition(q)return q.SyncToAudio.Audio.Sound.TimePosition end function O.Process(V,q,O)if V.SyncToAudio then if V.SyncToAudio.Audio~=nil and V.SyncToAudio.Audio.IsDestroyed then V:_attemptOnEnd()return end end local d=V:getSchemaProcessorTimePosition(q)local u=O+V.TimeLength if d>=u then V:_attemptOnEnd()return end q.Maid:add(V,"\083\101\101\107\070\108\097\103")V.Video=V:_constructVideo(V.VideoId)if not V.Video.IsLoaded then print("\076\111\097\100\105\110\103 \118\105\100\101\111")repeat V.task.wait()until V.IsCancelled or V.Video.IsLoaded end if not V.IsCancelled then print("\086\105\100\101\111 \108\111\097\100\101\100")end if V.SyncToAudio then while(V.SyncToAudio.Audio and(not V.SyncToAudio.Audio.IsDestroyed and not V.IsCancelled))and(V.SyncToAudio.Audio and(V.SyncToAudio.Audio.Sound==nil or V.SyncToAudio.Audio.Sound and V:getCurrentSoundTimePosition()<O))do V.task.wait()end end local U=q.timePosition.Value-O V.Video.TimePosition=U local S=V.Video.Ended:Connect(function()V:_attemptOnEnd()end)if V.captionButtonConnection then q.Maid:add(V.captionButtonConnection)end V.Video:Play()if V.Captions then SafeSpawn.new(function()V.CaptionsModule:Run()q.Maid:add(V.CaptionsModule,"\067\108\101\097\110")end)end local L=RunService.Heartbeat:Connect(function()V.CurrentSoundIntensityRatio=V:_calculateCurrentSoundIntensityRatio(V.Video)end)q.Maid:add(S)q.Maid:add(L)q.Maid:add(V.Video)q.Maid:add(V.CCButton)q.Maid:add(V.SurfaceGui)if not V.IsCancelled then V:_attemptOnStart()end end function O.SeekFlag(q)q.IsCancelled=true end return O
-- TODO add assertion for face string and enum
local function _assert(data)
	if data.SyncToAudio then
		assert(
			data.SyncToAudio.Audio ~= nil,
			"Failed to create config | expected an Audio for SyncToAudio, but received nil"
		)
		assert(
			data.SyncToAudio.StartAtAudioTime ~= nil,
			"Failed to create config | expected a StartAtAudioTime for SyncToAudio, but received nil"
		)
	else
		assert(
			data.StartTime ~= nil,
			"Failed to create config | expected config.StartTime or config.SyncToAudio, but received nil"
		)
	end

	assert(data.Adornee ~= nil, "Invalid Adornee | part expected got nil")
	assert(type(data.VideoId) == "string", ("Invalid VideoId | string expected got " .. type(data.VideoId)))
	if data.OnStart then
		assert(type(data.OnStart) == "function", ("Invalid OnStart | function expected got " .. type(data.OnStart)))
	end
	if data.OnEnd then
		assert(type(data.OnEnd) == "function", ("Invalid OnEnd | function expected got " .. type(data.OnEnd)))
	end

	if data.Face then
		assert(typeof(data.Face) == "EnumItem", ("Invalid Face Enum | enum expected got " .. typeof(data.Face)))
	end

	if data.Captions then
		local CaptionString = data.Captions.CaptionString
		assert(
			CaptionString ~= nil and type(CaptionString) == "string",
			("Invalid CaptionString | string expected got " .. type(CaptionString))
		)
	end
end

local Video = {}
Video.__index = Video
Video.Type = "Video"

Video.task = task

function Video:_constructVideo(videoId)
	self.SurfaceGui = Instance.new("SurfaceGui")
	-- TODO document this is a client only config
	local playerGui = Players.LocalPlayer:WaitForChild("PlayerGui")
	self.SurfaceGui.Adornee = self.Adornee
	self.SurfaceGui.Face = self.Face
	self.SurfaceGui.Name = self.Adornee.Name
	self.SurfaceGui.Parent = playerGui

	if self.SurfaceGuiProperties then
		for prop, value in pairs(self.SurfaceGuiProperties) do
			self.SurfaceGui[prop] = value
		end
	end

	self.VideoFrame = Instance.new("VideoFrame")
	self.VideoFrame.Video = videoId
	self.VideoFrame.Size = UDim2.new(1, 0, 1, 0)
	self.VideoFrame.Parent = self.SurfaceGui

	if self.Captions then
		self.VideoFrame:SetAttribute(enums.Attribute.Captions, self.Captions.CaptionString or "")
		self.CaptionsModule = CaptionsModule.new(self.VideoFrame)

		if self.CCButton then
			self.CCButton = self.CCButton:Clone()
		else
			self.CCButton = script.CCButton:Clone()
		end
		self.CCButton.Parent = self.SurfaceGui

		local captionLabel = self.CaptionsModule.CaptionLabel
		self.captionButtonConnection = self.CCButton.Activated:Connect(function()
			local areCaptionsVisible = captionLabel.Visible
			if areCaptionsVisible then
				self.CCButton.Image = ccOffIcon
			else
				self.CCButton.Image = ccIcon
			end
			captionLabel.Visible = not areCaptionsVisible
		end)
	end

	return self.VideoFrame
end

function Video:_calculateCurrentSoundIntensityRatio(video)
	local loudestPlayback = self.LoudestPlayback
	local loudness = video.volume
	self.LoudestPlayback = math.max(loudness, loudestPlayback)
	return loudness / self.LoudestPlayback
end

function Video.new(data)
	_assert(data)

	local self = setmetatable({}, Video)

	self.OnStart = data.OnStart or function(_config) end
	self.OnEnd = data.OnEnd or function(_config) end
	self.CurrentSoundIntensityRatio = 1
	self.LoudestPlayback = 1
	self.IsCancelled = false
	self.SyncToAudio = data.SyncToAudio
	self.VideoId = data.VideoId
	self.Adornee = data.Adornee
	self.Face = data.Face or Enum.NormalId.Top
	self.TimeLength = data.TimeLength
	self.SurfaceGuiProperties = data.SurfaceGuiProperties
	self.Captions = data.Captions
	self.CaptionsModule = data.CaptionsModule
	self.StartTime = data.StartTime

	if self.SyncToAudio then
		self.StartTime = self.SyncToAudio.Audio.StartTime + self.SyncToAudio.StartAtAudioTime
	end

	return self
end

function Video:_attemptOnStart()
	if self.OnStart ~= nil then
		SafeSpawn.new(function()
			self:OnStart()
		end)
	end
end

function Video:_attemptOnEnd()
	if self.OnEnd ~= nil then
		SafeSpawn.new(function()
			self:OnEnd()
		end)
	end
end

function Video:getSchemaProcessorTimePosition(schema)
	return schema.timePosition.Value
end

function Video:getCurrentSoundTimePosition()
	return self.SyncToAudio.Audio.Sound.TimePosition
end

function Video:Process(schemaProcessor, startTime)
	if self.SyncToAudio then
		if self.SyncToAudio.Audio ~= nil and self.SyncToAudio.Audio.IsDestroyed then
			self:_attemptOnEnd()
			return
		end
	end

	local currentTime = self:getSchemaProcessorTimePosition(schemaProcessor)
	local timeVideoFinishes = (startTime + self.TimeLength)
	if currentTime >= timeVideoFinishes then
		self:_attemptOnEnd()
		return
	end

	schemaProcessor.Maid:add(self, "SeekFlag")
	self.Video = self:_constructVideo(self.VideoId)

	if not self.Video.IsLoaded then
		print("Loading video")
		repeat
			self.task.wait()
		until self.IsCancelled or self.Video.IsLoaded
	end

	if not self.IsCancelled then
		print("Video loaded")
	end

	if self.SyncToAudio then
		while
			(self.SyncToAudio.Audio and not self.SyncToAudio.Audio.IsDestroyed and not self.IsCancelled)
			and (
				self.SyncToAudio.Audio
				and (
					self.SyncToAudio.Audio.Sound == nil
					or (self.SyncToAudio.Audio.Sound and self:getCurrentSoundTimePosition() < startTime)
				)
			)
		do
			self.task.wait()
		end
	end

	local timePositionOffset = schemaProcessor.timePosition.Value - startTime
	self.Video.TimePosition = timePositionOffset

	local videoOnEndConnection = self.Video.Ended:Connect(function()
		self:_attemptOnEnd()
	end)

	if self.captionButtonConnection then
		schemaProcessor.Maid:add(self.captionButtonConnection)
	end

	self.Video:Play()

	if self.Captions then
		SafeSpawn.new(function()
			self.CaptionsModule:Run()
			schemaProcessor.Maid:add(self.CaptionsModule, "Clean")
		end)
	end

	local intensityRatioCalculatorConnection = RunService.Heartbeat:Connect(function()
		self.CurrentSoundIntensityRatio = self:_calculateCurrentSoundIntensityRatio(self.Video)
	end)

	schemaProcessor.Maid:add(videoOnEndConnection)
	schemaProcessor.Maid:add(intensityRatioCalculatorConnection)
	schemaProcessor.Maid:add(self.Video)
	schemaProcessor.Maid:add(self.CCButton)
	schemaProcessor.Maid:add(self.SurfaceGui)

	if not self.IsCancelled then
		self:_attemptOnStart()
	end
end

function Video:SeekFlag()
	self.IsCancelled = true
end

return Video
