local common = LibStub("LibAddon"):GetAddon("common")
local tvavatarlisttab = LibStub("LibAddon"):NewAddon("tvavatarlisttab", "LibEvent", "LibTimer")

local default_db = {
	_uid = nil,
	_player_name = "",			--自己的名字
	_MicrophoneMute = false,	--麦克风静音状态
};

-- 初始化函数
function tvavatarlisttab:OnInitialize()
	self:DisableDebug();
	-- self:EnableDebug();
	self:print("OnInitialize");
	self.db = default_db;
	
	self:init_wnd();
	self:RegisterEvents();
	self:RegisterMessages();
	
	local icon_arry = {
		"set:YYUI image:TabUsersIconNormal",
		"set:YYUI image:TabUsersIconSelected",
		"set:YYUI image:TabUsersIconSelected"
	}
	self:SendMessage("MSG_TEAMVOICE_ADD_TAB_PAGE", self.obj_main_wnd, icon_arry);
	
end

function tvavatarlisttab:init_wnd()
	self.wnd_mgr = CEGUI.WindowManager:getSingleton();
	self.img_mgr = CEGUI.ImagesetManager:getSingleton()
	self.img_set = self.img_mgr:get("YYUI")
	self.obj_main_wnd = self.wnd_mgr:getWindow("AvatarlistFrame");
	self.obj_avatar_list = self.wnd_mgr:getWindow("Avatarlist");
	self.obj_avatar_list = CEGUI.toListbox(self.obj_avatar_list);
	self.obj_avatar_list:setSortingEnabled(false)
	self.obj_top_edge = self.wnd_mgr:getWindow("AvatarlistFrame/bg/head");
	self.obj_bottom_edge = self.wnd_mgr:getWindow("AvatarlistFrame/bg/bottom");
	
	self.obj_avatar_list:setAutoShowHorzScrollbar(false)
	self.obj_avatar_list:setTooltipType("YY/Tooltip")
	self.obj_vscrollbar = self.obj_avatar_list:getVertScrollbar()
	self.obj_vscrollbar:setTooltipType("YY/Tooltip")
	local thumb = self.obj_vscrollbar:getThumb()
	if thumb then
		thumb:setTooltipType("YY/Tooltip")
	end
end

-- 注册控件事件
function tvavatarlisttab:RegisterEvents()
	self.obj_avatar_list:subscribeEvent("IconMouseButtonDown", self.on_icon_mouse_button_down, self);
	self:RegisterEvent("YYT_TO_PIP_LOGIN_TEAM", "on_login");
	self:RegisterEvent("YYT_TO_PIP_MINIYYSTATE", "on_miniyy_state");
end

-- ListBox的Item中的图标被点的消息响应 （开关某个玩家的声音）
function tvavatarlisttab:on_icon_mouse_button_down(args)
	local mouse_args = CEGUI.toMouseEventArgs(args)
	local itemIndex  = mouse_args.position.x
	local iconIndex  = mouse_args.position.y
	self:print("itemIndex="..itemIndex.." iconIndex="..iconIndex)
	local item = CEGUI.toListboxExtraItem( self.obj_avatar_list:getListboxItemFromIndex(itemIndex) )
	if item ~= nil then
		local uid = item:getID();

		if (item.avatar_data._animIcon:ismute())then
			item.avatar_data._animIcon:demute();
			TeamTalkClient:getSingleton():IgnoreVoice(uid, false);
		else
			item.avatar_data._animIcon:mute();
			TeamTalkClient:getSingleton():IgnoreVoice(uid, true);
		end
	end
end

function tvavatarlisttab:on_login(event, uid)
	self:debug( ("on_login uid:%s"):format(tostring(uid)));
	self.db.uid = uid;
end

function tvavatarlisttab:on_miniyy_state(event, uid, sid)
	self:debug( ("on_miniyy_state uid:%s, sid:%s"):format(tostring(uid), tostring(sid)));
	self.db.uid = uid;
end

-- 注册消息事件
function tvavatarlisttab:RegisterMessages()
	self:RegisterMessage("TEAMVOICE_CLEARDB", "notify_teamvoice_cleardb");
	self:RegisterMessage("TEAMVOICE_INIT_PLAYER", "notify_teamvoice_init_player");
	self:RegisterMessage("TEAMVOICE_DELETE_PLAYER", "notify_teamvoice_delete_player");
	self:RegisterMessage("TEAMVOICE_PERFECT_PLAYER", "notify_teamvoice_perfect_player");
	self:RegisterMessage("TEAMVOICE_LEAVE_PLAYER", "notify_teamvoice_leave_player");
	self:RegisterMessage("TEAMVOICE_TALKING_PLAYER", "notify_teamvoice_talking_player");
	self:RegisterMessage("MSG_TVSHOW_PAGE_EDGE", "on_show_edge");
end

-- 显示上下边沿黑线
function tvavatarlisttab:on_show_edge(event, mode)
	if mode ~= nil then
		if mode == 0 then
			self.obj_top_edge:show()
			self.obj_bottom_edge:hide()
		elseif mode == 1 then
			self.obj_top_edge:hide()
			self.obj_bottom_edge:show()
		end
	end
end

function tvavatarlisttab:notify_teamvoice_cleardb(event)
	self.db_player_name = nil;
	self.db_MicrophoneMute = false;
end

function tvavatarlisttab:notify_teamvoice_init_player(event, player, x, y)
	if player then
		local avatar_data = {
			_animIcon = nil,
			_item = nil,
		};

		player.avatar_data = avatar_data;
	end
end

function tvavatarlisttab:notify_teamvoice_delete_player(event, player)
	if (player.avatar_data ~= nil) then
		-- 移除item, 更新动画列表
		if (player.avatar_data._item ~= nil) then
			local index = self.obj_avatar_list:getItemIndex(player.avatar_data._item)
			self.obj_avatar_list:removeItem(player.avatar_data._item);
			player.avatar_data._item.avatar_data = nil;		-- 确保提早回收avatar_data
			player.avatar_data._item = nil;
		end
		if (player.avatar_data._animIcon ~= nil) then
			player.avatar_data._animIcon:stop();
			player.avatar_data._animIcon = nil;
		end
		
		player.avatar_data = nil;
	end
end

function tvavatarlisttab:notify_teamvoice_perfect_player(event, player)
	if (player.avatar_data ~= nil) then
		if (player._another_name ~= nil) then
			self:add_item(player.avatar_data, player._another_name, player._uid);
		else
			self:add_item(player.avatar_data, player._player_name, player._uid);
		end
	end
end

function tvavatarlisttab:notify_teamvoice_leave_player(event, player)
	self:notify_teamvoice_delete_player(event, player);
end

function tvavatarlisttab:notify_teamvoice_talking_player(event, player, talking)
	if (player.avatar_data ~= nil) then
		if player.avatar_data._item ~= nil then
			if talking == 1 then
				player.avatar_data._animIcon:start()
			else
				player.avatar_data._animIcon:stop()
			end
		end
	end
end

function tvavatarlisttab:add_item(avatar_data, name, id)
	self:print("add_item id="..id.." name="..name.." player_name="..self.db._player_name.." MicrophoneMute="..tostring(self.db._MicrophoneMute))
	local item = CEGUI.createListboxExtraItem( name, id )
	item:setTooltipText("[colour='FF000000']"..name)
	item:setTextParsingEnabled(false)
	item:setTextColours(CEGUI.colour( 201/255, 202/255, 181/255, 1 ))
	item:setMouseOnColours(CEGUI.colour( 255/255, 255/255, 255/255, 1 ))
	item:setSelectionColours(CEGUI.colour( 255/255, 255/255, 255/255, 1 ))
	item:setMouseOnBrushImage("YYUI", "ListboxMouseonBrush")
	item:setSelectionBrushImage( "YYUI", "ListboxSelectionBrush")
	item:setHeightStep(1.0)
	item:setAutoWidthShow(true)
	item:setSingleLine(true)
	item:setLeftStep(7)
	
	local image = self.img_set:getImage( "MsgWndLogoSpeak" );
	item:addIcon( image, image:getWidth(), image:getHeight() )

	-- 递归引用
	item.avatar_data = avatar_data;

	self.obj_avatar_list:addItem( item )
	avatar_data._animIcon = self.AnimIcon:new( item );
	avatar_data._item = item;

	if self.db._MicrophoneMute and name == self.db._player_name then
		avatar_data._animIcon:mute();
	end
end
