local Component = class("Component")

function Component:ctor()
end

function Component:init()
end

function Component:getBaseObject()
    return self.baseObject
end

function Component:getGameObject()
    return self.baseObject:getGameObject()
end

function Component:getUIMap()
    return self.baseObject:genAllChildren()
end

function Component:bind(data, fieldName, bindFunc, immediately)
    self:_addOnDestroyCallback()
	if not self._baseBindData then
		self._baseBindData = {}
	end
	if not self._baseBindData[data] then
		self._baseBindData[data] = {}
	end
	data:bind(fieldName, self, bindFunc, immediately)
 	table.insert(self._baseBindData[data], fieldName)
end

function Component:unBind(data, fieldName)
	if self._baseBindData and self._baseBindData[data] then
		for i, field in ipairs(self._baseBindData[data]) do
			if field == fieldName then
				data:unBind(field, self)
				table.remove(self._baseBindData[data], i)
				break
			end
		end
	end
end

function Component:unBindAll()
	if not self._baseBindData then
		return
	end

	for data, fields in pairs(self._baseBindData) do
		for _, field in ipairs(fields) do
			data:unBind(field, self)
		end
	end
	self._baseBindData = nil
end

function Component:isDestroyed()
    return self.baseObject:isDestroyed()
end

function Component:onDestroy()
end

function Component:_init(baseObject)
    self.baseObject = baseObject
    if self.onDestroy ~= Component.onDestroy then -- 说明重写了onDestroy
        self:_addOnDestroyCallback()
    end
    self:init()
end

function Component:_addOnDestroyCallback()
    if self._addOnDestroyFlag then
        return
    end
    self._addOnDestroyFlag = true
    self.baseObject:addOnDestroyCallback(function()
        self:unBindAll()
        self:onDestroy()
    end)
end

return Component