local BaseObject = require "app/bf/unity/base_object"

local BaseScene = {}

function BaseScene:ctor()
end

function BaseScene:init()
end

function BaseScene:onClose()
end

function BaseScene:closeLoadingAuto()
	return true
end

function BaseScene:addCloseLoadingCallback(callback)
	self.closeLoadingCallback = callback
end

function BaseScene:closeLoading(callback)
	local success = UIManager:closeLoading(function()
		if callback then
			callback()
		end
		if self.closeLoadingCallback then
			self.closeLoadingCallback()
			self.closeLoadingCallback = nil
		end
	end)
	if success then -- 避免重复调用
		self:enableTouch()
	end
end

function BaseScene:getResPath()
	return "assets/scenes/common_scene.unity"
end

function BaseScene:isClosed()
	return self._isAlreadyClosed
end

function BaseScene:setRootActive(enable)
	self.root:setActive(enable)
end

function BaseScene:addEventListener(key, func, priority)
	local tag = EventManager:addEventListener(key, func, priority)
	self._baseEventListeners = self._baseEventListeners or {}
	self._baseEventListeners[key] = tag
end

function BaseScene:removeEventListener(key)
	if self._baseEventListeners and self._baseEventListeners[key] then
		EventManager:removeEventListener(key, self._baseEventListeners[key])
		self._baseEventListeners[key] = nil
	end
end

function BaseScene:scheduleGlobal(func, inter)
	local sid = SchedulerManager:scheduleGlobal(func, inter)
	if self._schedulerIds == nil then
		self._schedulerIds = {}
	end
	table.insert(self._schedulerIds, sid)
	return sid
end

function BaseScene:performWithDelayGlobal(func, delay)
	local sid = SchedulerManager:performWithDelayGlobal(func, delay)
	if self._schedulerIds == nil then
		self._schedulerIds = {}
	end
	table.insert(self._schedulerIds, sid)
	return sid
end

function BaseScene:unscheduleGlobal(sid)
	if self._schedulerIds == nil then
		return
	end
	for k, v in ipairs(self._schedulerIds) do
		if v == sid then
			table.remove(self._schedulerIds, k)
			break
		end
	end
	SchedulerManager:unscheduleGlobal(sid)
end

function BaseScene:enableTouch()
	UIManager:enableTouch()
end

function BaseScene:disableTouch()
	UIManager:disableTouch()
end

function BaseScene:_init(initParams)
	local gameObject = CS.UnityEngine.GameObject("scene_root")
	self.root = BaseObject:create()
	self.root:initWithGameObject(gameObject)
	self.root:setPosition(0, 0, 0)
	self:init(initParams)
end

function BaseScene:_onClose()
	self:onClose()
	self._isAlreadyClosed = true
	self:_baseClear()
	self:_destroy()
end

function BaseScene:_baseClear()
	if self._baseEventListeners then
		for key, tag in pairs(self._baseEventListeners) do
			EventManager:removeEventListener(key, tag)
		end
		self._baseEventListeners = nil
	end

	if self._schedulerIds then
		for k, v in ipairs(self._schedulerIds) do
			SchedulerManager:unscheduleGlobal(v)
		end
		self._schedulerIds = nil
	end
end

function BaseScene:_destroy()
	if self.root then
		self.root:destroy()
		self.root = nil
	end
end

return BaseScene