

local guildOk = false;
local Inventory = nil;
local InventoryCount = 0;

local pnlMain = nil;
local pnlMainDNDId = 201;
local buttons = {};
local buttonPrototype = nil;
local silenceButton = nil;

local layout = {};
local items = {};

local firstRun = true;
local targetRestricted = false;
local itemCount = 0;


function UpdateItem(index)
	if not items[index] then
		return
	end
	
	local itemId = items[index];
	local button = layout[index];
	local info = avatar.GetItemInfo( itemId );
	local stackCount = info.stackCount;
	local spellInfo = avatar.GetSpellInfo( info.spellId )	
	local name = string.lower(GetItemName(itemId));	
	
	if (spellInfo.cooldownRemainingMs == 0 ) then
		SetButtonCaption ( button, info.stackCount );
	else
		if spellInfo.cooldownRemainingMs > 99000 then
			SetButtonCaption ( button, '~' );
		else
			SetButtonCaption ( button, GetCooldownString(spellInfo.cooldownRemainingMs));
		end
	end
	
	local disable = (targetRestricted and button == silenceButton);
	button:Enable( not disable and spellInfo.cooldownRemainingMs == 0 );
end

function modulus ( a, b ) 
	return a - (math.floor(a/b) * b );
end

function AddButton ( idx, itemId )
	local prototype = buttonPrototype:GetWidgetDesc();
	local newButton = mainForm:CreateWidgetByDesc( prototype )
	local pack = {};
	pack.button = newButton;
	pack.itemId = itemId;
	pack.idx = idx;
	
	layout[idx] = newButton;
	items[idx] = itemId;
	
	pnlMain:AddChild(newButton);
	
	--Log(idx);
	local Placement = newButton:GetPlacementPlain();	
	--if ( HorizontalGrowth ) then
	local hidx = idx - 1;
	local vidx = 0;
	if ( MaxCols ) then
		vidx = math.floor(hidx / MaxCols);
		hidx = modulus(hidx, MaxCols);
		
		--Log (hidx .. ':'.. vidx)
	end
	Placement.posX = 14 + hidx * IconSize;
	Placement.posY = vidx * IconSize +  15;
	--else
	--	Placement.posX = 15;
	--	Placement.posY = 14 + (idx - 1) * IconSize;
	--end

	
	Placement.sizeY = IconSize;
	Placement.sizeX = IconSize;
	
	local btnName = 'btnItem'..tostring(idx);
	newButton:SetName( btnName );
	--Log(btnName );
	newButton:SetPlacementPlain(Placement);
	SetButtonIdx( idx, itemId )
	newButton:Show( true );
	newButton:Enable( itemId  ~= nil)
end

function SetButtonIdx( idx, itemId ) 
	items[ idx ] = itemId;
	if (itemId) then
		local newButton = layout[idx];
		SetBackgroundTextureFromItem(newButton, itemId);
		SetButtonCaption(newButton, GetItemCount(itemId) );
		newButton:Enable( true );
	end
end

function inTablePartial(tbl, name)
	if name == '' then
		return false
	end
	
    for key, value in pairs(tbl) do
		if (value ~= '') then
			if string.find(name, value) then
				return key
			end
		end
    end
    return false
end

function UpdatePanelSize ( count )
	local pPlacement = pnlMain:GetPlacementPlain();
	local hCount = count;
	local vCount = 1;
	--if HorizontalGrowth then
		if ( MaxCols ) then
			if ( hCount > MaxCols ) then
				vCount = math.ceil ( hCount / MaxCols );
				hCount = MaxCols;
			end
		end
		pPlacement.sizeX = hCount * IconSize + 28;
		pPlacement.sizeY = vCount * IconSize + 30;
	--else
	--	pPlacement.sizeX = IconSize + 30;
	--	pPlacement.sizeY = count * IconSize + 28;
	--end
	
	pnlMain:SetPlacementPlain(pPlacement);
end

function RecheckInventory()
	Inventory = avatar.GetInventoryItemIds();
	InventoryCount = avatar.GetInventorySize() - 1;
	for k,v in layout do
		v:DestroyWidget();
	end
	
	local sorted = {};
	layout = {};
	items = {};
	
	
	--local itemsCount = table.getn(ItemNames);
	
	
	--local panelSize = table.getn(ItemNames);
	--for index = 1, panelSize do
		--AddButton ( index , nil )
	--end
	
	for index = 0, InventoryCount do
		local itemId = Inventory[index];
		if (itemId) then
			local name = string.lower(GetItemName( itemId ));

			local pos = inTablePartial(ItemNames, name);
			if (pos) then
				sorted[pos] = {};
				sorted[pos].itemId = itemId;
				sorted[pos].name = name;
			end
		end
	end
	
	local count = table.getn(sorted);
	local tempPos = 1;
	for k, pack in sorted do
		local itemId = pack.itemId;
		local name = pack.name;
		AddButton ( tempPos, itemId );
		tempPos = tempPos + 1;
		--SetButtonIdx( pos, itemId );
		if (name == 'Обычный экстракт удушника') then
			silenceButton = layout [ tempPos ];
		end
	end
	
	UpdatePanelSize ( tempPos  - 1)

	firstRun = false;
end

function OnEVENT_SECOND_TIMER(params)
	ClearChat();
	if (Self == nil) then 
		if InitAvatar() then
			RegisterAll();
		end
	else 
		UpdateItems(); 
	end
end


function OnEVENT_UNKNOWN_SLASH_COMMAND(params)
	local cmd = WStringToString(params.text);
	if (cmd == '/ireset') then
		Log('/ireset - Resetting panel position to 200:200');
		local Placement = pnlMain:GetPlacementPlain()
		Placement.posY = 200;
		Placement.posX = 200;
		pnlMain:SetPlacementPlain(Placement) 
		return;
	end
	if cmd == "/pip list" then
		for i,j in ItemNames do
			Log(j)
		end
		return;
	end
	if cmd == "/pip ddnd" then
		DnD:Enable(pnlMain, false)
		return;
	end
	if cmd == "/pip ednd" then
		DnD:Enable(pnlMain, true)
		return;
	end
		
	if string.sub(cmd, 1, 5) == "/pip " then
		local name = string.lower(string.sub(cmd, 6))
		local found = 0
		for i,v in pairs(ItemNames) do
			if v == name then
				table.remove(ItemNames, i)
				found = 1
				Log(name..' removed from the list');
			end
		end
		if found == 0 then
			table.insert(ItemNames, name)
			Log(name..' added to the list');
		end
		userMods.SetAvatarConfigSection("PIP", ItemNames)
		common.StateUnloadManagedAddon( "UserAddon/"..common.GetAddonName() )
		common.StateLoadManagedAddon( "UserAddon/"..common.GetAddonName() )
	end
	
end

function UpdateItems()
	for k,itemId in items do
		UpdateItem (k );
	end
end

function UseItem(itemId, idx)
	if (not itemId) then
		RecheckInventory();
		return;
	end
	
	
	if (GetItemCount ( itemId ) > 0) then
		avatar.UseItem(itemId);
		UpdateItem( idx );
	end
end

function ButtonIndexFromName ( name )
	for k,v in layout do
		if (v:GetName() == name) then
			return k;
		end
	end
	return nil;
end

function OnButtonClick(params)
	if not DnD:IsDragging() then
		local p = ButtonIndexFromName (tostring(params.sender));
		local itemId = items[p];
		--Log(tostring(itemId));
		UseItem( itemId , p );
	end
end

function OnEVENT_INVENTORY_CHANGED(params)
	RecheckInventory();
end

function EnableSilenceItems( toggle )
	if not silenceButton then
		return
	end
	silenceButton:Enable ( toggle );
end

function OnEVENT_AVATAR_PRIMARY_TARGET_CHANGED(params)
	local target = unit.GetTarget( Self );
	if (not target) then
		targetRestricted = false;
		EnableSilenceItems( not targetRestricted );
		return
	end
	
	--DRUID,MAGE,NECROMANCER,PALADIN,PRIEST,PSIONIC,STALKER,WARRIOR
	local class = unit.GetClass(target).className;
	local restrictedClasses = {'PALADIN', 'STALKER', 'WARRIOR', 'BARD'};
	targetRestricted = inTable(restrictedClasses, class) ~= false;
	
	EnableSilenceItems( not targetRestricted );
end

function OnBtnItem1 () 
	Log ( 'OnBtnItem1' );
	local p = 1;
	local itemId = items[p];
	--Log(tostring(itemId));
	UseItem( itemId , p );
end

function RegisterAll()
	RecheckInventory();
	
	common.RegisterEventHandler( OnEVENT_UNKNOWN_SLASH_COMMAND, "EVENT_UNKNOWN_SLASH_COMMAND");
	common.RegisterEventHandler( OnEVENT_INVENTORY_CHANGED, "EVENT_INVENTORY_CHANGED");
	common.RegisterEventHandler( OnEVENT_INVENTORY_CHANGED, "EVENT_INVENTORY_ITEM_CHANGED");
	
	common.RegisterEventHandler( OnEVENT_AVATAR_PRIMARY_TARGET_CHANGED, "EVENT_AVATAR_PRIMARY_TARGET_CHANGED");
	
	DnD:Init(pnlMainDNDId, pnlMain, nil, true, false, nil);

	common.RegisterReactionHandler( OnButtonClick, "OnButtonClick" )
	--common.RegisterReactionHandler( OnBtnItem1, "OnBtnItem1" )
	Log('Ready');
end

function Init()
	pnlMain = mainForm:GetChildChecked("pnlMain", false);
	buttonPrototype = pnlMain:GetChildChecked("btnPrototype", false);	
	
	if not userMods.GetAvatarConfigSection("PIP") then
		userMods.SetAvatarConfigSection("PIP", ItemNames)
	else ItemNames = userMods.GetAvatarConfigSection("PIP") end
	
	if InitAvatar() then
		RegisterAll();
	end
	
	common.RegisterEventHandler( OnEVENT_SECOND_TIMER, "EVENT_SECOND_TIMER");
	
	
end
--------------------------------------------------------------------------------
Init()
--------------------------------------------------------------------------------
