require "class"
local InvSlot = require "widgets/invslot"
local TileBG = require "widgets/tilebg"
local Image = require "widgets/image"
local Widget = require "widgets/widget"
local EquipSlot = require "widgets/equipslot"
local ItemTile = require "widgets/itemtile"
local Text = require "widgets/text"
local ThreeSlice = require "widgets/threeslice"


local HUD_ATLAS = "images/hud.xml"
--local W = 68
--local SEP = 12
--local YSEP = 8
--local INTERSEP = 28

local CURSOR_STRING_DELAY = 10
local TIP_YFUDGE = 16
local HINT_UPDATE_INTERVAL = 2.0 -- once per second

local Inventorybarcloneplayer = Class(Widget, function(self, owner)
    Widget._ctor(self, "Inventory")
    self.owner = owner
	
	self.plnum = self.owner.plnum
	
	self.w = 68
	self.sep = 12
	self.ysep = 8
	self.intersep = 28
	
	if self.plnum == 2 then
		self.actbutton = "[DELETE]"
		self.altactbutton = "[END]"
	elseif self.plnum == 3 then
		self.actbutton = "[P]"
		self.altactbutton = "[N]"
		self.sep = 8 
		self.intersep = 17
	end
	
	local W = self.w
	local SEP = self.sep
	local YSEP = self.ysep
	local INTERSEP = self.intersep	
	

	self.out_pos = Vector3(0,W,0)
	self.in_pos = Vector3(0,W*1.5,0)

	self.base_scale = .6
	self.selected_scale = .45

    self:SetScale(self.base_scale)
    self:SetPosition(0,-16,0)

    self.inv = {}
    self.backpackinv = {}
    self.equip = {}
    self.equipslotinfo = {}

	self.root = self:AddChild(Widget("root"))
	local owscale = 0.001
	self.bg = self.root:AddChild(Image(HUD_ATLAS, "equip_slot.tex"))
	self.bg:SetScale(owscale,owscale,owscale)
	--self.bg = self.root:AddChild(ThreeSlice(HUD_ATLAS, "inventory_corner.tex", "inventory_filler.tex"))
	
	self.bgcover = self.root:AddChild(Image(HUD_ATLAS, "equip_slot.tex"))
	self.bgcover:SetScale(owscale,owscale,owscale)
	
    self.hovertile = nil
    self.cursortile = nil
	self.open = true
	self.repeat_time = .2

	--this is for the keyboard / controller inventory controls
	self.actionstring = self.root:AddChild(Widget("actionstring"))
	self.actionstring:SetScaleMode(SCALEMODE_PROPORTIONAL)


	self.actionstringtitle = self.actionstring:AddChild(Text(TALKINGFONT, 22))
	
	---inst.plclr[1]
	local clr = self.owner.plclr
	self.actionstringtitle:SetColour(clr[1], clr[2], clr[3], 1)
	
	self.normal_text_colour = {clr[1], clr[2], clr[3], 1}
	
	--self.wet_text_colour = {150/255, 160/255, 225/255, 1}
	self.wet_text_colour = {clr[1]/2+75/255, clr[2]/2+80/255, clr[3]/2+115, 1}
	
	
	self.actionstringbody = self.actionstring:AddChild(Text(TALKINGFONT, 15))
	self.actionstringbody:EnableWordWrap(true)
	self.actionstring:Hide()

	--default equip slots
	self:AddEquipSlot(EQUIPSLOTS.HANDS, HUD_ATLAS, "equip_slot.tex")
	self:AddEquipSlot(EQUIPSLOTS.BODY, HUD_ATLAS, "equip_slot_body.tex")
	self:AddEquipSlot(EQUIPSLOTS.HEAD, HUD_ATLAS, "equip_slot_head.tex")

    self.inst:ListenForEvent("builditem", function(inst, data) self:OnBuild() end, self.owner)
    self.inst:ListenForEvent("itemget", function(inst, data) self:OnItemGet(data.item, self.inv[data.slot], data.src_pos) end, self.owner)
    self.inst:ListenForEvent("equip", function(inst, data) self:OnItemEquip(data.item, data.eslot) end, self.owner)
    self.inst:ListenForEvent("unequip", function(inst, data) self:OnItemUnequip(data.item, data.eslot) end, self.owner)
    self.inst:ListenForEvent("newactiveitem", function(inst, data) self:OnNewActiveItem(data.item) end, self.owner)
    self.inst:ListenForEvent("itemlose", function(inst, data) self:OnItemLose(self.inv[data.slot]) end, self.owner)
    self.inst:ListenForEvent("setoverflow", function(inst, data) self:Rebuild() end, self.owner)

    self.root:SetPosition(self.in_pos)
    self:StartUpdating()

    self.actionstringtime = CURSOR_STRING_DELAY

	self.openhint = self:AddChild(Text(UIFONT, 32))
	self.openhint:SetRegionSize(300, 60)
	self.openhint:SetHAlign(ANCHOR_LEFT)
	self.openhint:SetPosition(940, 70, 0)
	
    self.hint_update_check = HINT_UPDATE_INTERVAL
    
	self.inventoryshown=true
end)




function Inventorybarcloneplayer:AddEquipSlot(slot, atlas, image, sortkey)
	sortkey = sortkey or #self.equipslotinfo
	table.insert(self.equipslotinfo, {slot = slot, atlas = atlas, image = image, sortkey = sortkey})
	table.sort(self.equipslotinfo, function(a,b) return a.sortkey < b.sortkey end)
	self.rebuild_pending = true
end


local function BackpackGet(inst, data)
	local owner = inst.components.inventoryitem and inst.components.inventoryitem.owner
	
	if owner then
		local inv = owner.HUD.controls.inv
		if inv then
			inv:OnItemGet(data.item, inv.backpackinv[data.slot], data.src_pos)
		end
	end		
end

local function BackpackLose(inst, data)
	local owner = inst.components.inventoryitem and inst.components.inventoryitem.owner
	if owner then
		local inv = owner.HUD.controls.inv
		if inv then
			inv:OnItemLose(inv.backpackinv[data.slot])
		end
	end		
end

function Inventorybarcloneplayer:Rebuild()


	local W = self.w
	local SEP = self.sep
	local YSEP = self.ysep
	local INTERSEP = self.intersep	



	if self.cursor then
		self.cursor:Kill()
		self.cursor = nil
	end
	
	if self.toprow then
		self.toprow:Kill()
	end

	if self.bottomrow then
		self.bottomrow:Kill()
	end

	self.toprow = self.root:AddChild(Widget("toprow"))
	self.bottomrow = self.root:AddChild(Widget("toprow"))

    self.inv = {}
    self.equip = {}
	self.backpackinv = {}

    local y = self.owner.components.inventory.overflow and (W/2+YSEP/2) or 0
    local eslot_order = {}

    local num_slots = self.owner.components.inventory:GetNumSlots()
    local num_equip = #self.equipslotinfo
    local num_intersep = math.floor(num_slots / 5) + 1 
    local total_w = (num_slots + num_equip)*(W) + (num_slots + num_equip - 2 - num_intersep) *(SEP) + INTERSEP*num_intersep
    
    for k, v in ipairs(self.equipslotinfo) do
        local slot = EquipSlot(v.slot, v.atlas, v.image, self.owner)
        self.equip[v.slot] = self.toprow:AddChild(slot)
        local x = -total_w/2 + (num_slots)*(W)+num_intersep*(INTERSEP - SEP) + (num_slots-1)*SEP + INTERSEP + W*(k-1) + SEP*(k-1)
        
		if self.plnum == 2 then
			slot:SetPosition(x,0,0)
		else
			print("== CREATE EQUIP SLOT... = "..k.."  y =  "..x)
			slot:SetPosition(0,x*0.75,0)
			-- if k == 11 then
				-- x =  -total_w/2 + W/2 + interseps*(INTERSEP - SEP)
			-- end
			-- if k > 10 then
				-- slot:SetPosition(INTERSEP*1.5,x,0)
			-- end
		end
		--slot:SetPosition(0,x,0)
        table.insert(eslot_order, slot)
        
		local item = self.owner.components.inventory:GetEquippedItem(v.slot)
		if item then
			slot:SetTile(ItemTile(item))
		end

    end    
	
    for k = 1,num_slots do
        local slot = InvSlot(k, HUD_ATLAS, "inv_slot.tex", self.owner, self.owner.components.inventory)
        self.inv[k] = self.toprow:AddChild(slot)
        local interseps = math.floor((k-1) / 5)
        local x = -total_w/2 + W/2 + interseps*(INTERSEP - SEP) + (k-1)*W + (k-1)*SEP
		--local reserved_x = x
		if self.plnum == 2 then
			slot:SetPosition(x,0,0)
		else
			print("== CREATE SLOT... = "..k.."  y =  "..x)
			slot:SetPosition(0,x*0.75,0)
			-- if k == 11 then
				-- x =  -total_w/2 + W/2 + interseps*(INTERSEP - SEP)
			-- end
			-- if k > 10 then
				-- slot:SetPosition(INTERSEP*1.5,x,0)
			-- end
		end

		slot.top_align_tip = W*0.5 + YSEP

		local item = self.owner.components.inventory:GetItemInSlot(k)
		if item then
			slot:SetTile(ItemTile(item))
		end
        
    end


	local old_backpack = self.backpack
	if self.backpack then
		self.inst:RemoveEventCallback("itemget", BackpackGet, self.backpack)
		self.inst:ListenForEvent("itemlose", BackpackLose, self.backpack)
		self.backpack = nil
	end


	local new_backpack = self.owner.components.inventory.overflow
	local do_integrated_backpack = TheInput:ControllerAttached() and new_backpack

	if self.boatwidget then
		self.boatwidget:SetPosition(Vector3(700, do_integrated_backpack and 105 or 65, 0))
	end

	if do_integrated_backpack then
		local num = new_backpack.components.container.numslots



		local x = - (num * (W+SEP) / 2)
		--local offset = #self.inv >= num and 1 or 0 --math.ceil((#self.inv - num)/2)
		local offset = 1 + #self.inv - num

		for k = 1, num do
			local slot = InvSlot(k, HUD_ATLAS, "inv_slot.tex", self.owner, new_backpack.components.container)
			self.backpackinv[k] = self.bottomrow:AddChild(slot)

			slot.top_align_tip = W*1.5 + YSEP*2
			
			if offset > 0 then
				slot:SetPosition(self.inv[offset+k-1]:GetPosition().x,0,0)
			else
				slot:SetPosition(x,0,0)
				x = x + W + SEP
			end
			
			local item = new_backpack.components.container:GetItemInSlot(k)
			if item then
				slot:SetTile(ItemTile(item))
			end
			
		end
		
		self.backpack = self.owner.components.inventory.overflow
	    self.inst:ListenForEvent("itemget", BackpackGet, self.backpack)
	    self.inst:ListenForEvent("itemlose", BackpackLose, self.backpack)
	end

	if old_backpack	and not self.backpack then
		self:SelectSlot(self.inv[1])
		self.current_list = self.inv
	end

	--self.bg:Flow(total_w+60, 256, true)
	
	if do_integrated_backpack then
		self.bg:SetPosition(Vector3(0,-24,0))
	    self.bgcover:SetPosition(Vector3(0, -135, 0))
		self.toprow:SetPosition(Vector3(0,W/2 + YSEP/2,0))
		self.bottomrow:SetPosition(Vector3(0,-W/2 - YSEP/2,0))
		self.root:MoveTo(self.out_pos, self.in_pos, .5)
	else
		self.bg:SetPosition(Vector3(0, -64, 0))
	    self.bgcover:SetPosition(Vector3(0, -100, 0))
		self.toprow:SetPosition(Vector3(0,0,0))
		self.bottomrow:SetPosition(0,0,0)
		
		if TheInput:ControllerAttached() then
			self.root:MoveTo(self.in_pos, self.out_pos, .2)
		else
			self.root:SetPosition(self.out_pos)
		end
		
		
	end
	
	self.actionstring:MoveToFront()
	
	self:SelectSlot(self.inv[1])
	self.current_list = self.inv
	self:UpdateCursor()
	
	if self.cursor then
		self.cursor:MoveToFront()
	end


	self.rebuild_pending = false
end

function Inventorybarcloneplayer:OnUpdate(dt)
	if not self.owner then
		print("NO OWNER DELETE INVENTORY")
		GetPlayer().HUD.controls.Inventorybarcloneplayer:Kill()
		return
	end
	if not self.owner.components.playercontroller_3 then return end

	if GetPlayer().HUD ~= TheFrontEnd:GetActiveScreen() then return end
	if not GetPlayer().HUD.shown then return end

	if self.rebuild_pending == true then
		self:Rebuild()
		self:Refresh()
	end
	
	if self.inventoryshown==true and self.owner.components.playercontroller_3.inventoryshown == false then
		self:ScaleTo(self.base_scale, self.selected_scale,.1)
		self.inventoryshown=false 
	elseif self.inventoryshown==false and self.owner.components.playercontroller_3.inventoryshown == true then
		self:ScaleTo(self.selected_scale, self.base_scale,.1)
		self.inventoryshown=true 
	end--]]
	
	


	if self.active_slot and not self.active_slot.inst:IsValid() then
		self:SelectSlot(self.inv[1])
		
		self.current_list = self.inv
		
		if self.cursor then
			self.cursor:Kill()
			self.cursor = nil
		end
		
	end
	if not self.owner.components.playercontroller_3 then return end
	self:SelectSlotFromPC()
	self:UpdateCursor()
	
		
end


function Inventorybarcloneplayer:OffsetCursor(offset, val, minval, maxval, slot_is_valid_fn)
	if val == nil then
		val = minval
	else
		
		local idx = val
		local start_idx = idx

		repeat 
			idx = idx + offset
			
			if idx < minval then idx = maxval end
			if idx > maxval then idx = minval end

			if slot_is_valid_fn(idx) then 
				val = idx
				break
			end

		until start_idx == idx
	end
	
	return val
end

function Inventorybarcloneplayer:GetInventoryLists(same_container_only)
	if same_container_only then
		local lists = {self.current_list}

		if self.current_list == self.inv then
			table.insert(lists, self.equip)
		elseif self.current_list == self.equip then
			table.insert(lists, self.inv)
		end

		return lists
	else
		local lists = {self.inv, self.equip, self.backpackinv}

		local bp = self.owner.HUD:GetFirstOpenContainerWidget()
		if bp then
			table.insert(lists, bp.inv)
			if bp.boatEquip then 
				table.insert(lists, bp.boatEquip)
			end 
		end

		return lists
	end

end

function Inventorybarcloneplayer:CursorNav(dir, same_container_only)

	--GetPlayer().components.playercontroller:CancelDeployPlacement()

	if self:GetCursorItem() then
    	self.actionstringtime = CURSOR_STRING_DELAY
    	self.actionstring:Show()
    end


	if self.active_slot and not self.active_slot.inst:IsValid() then
		self.current_list = self.inv
		return self:SelectSlot(self.inv[1])
	end

	local lists = self:GetInventoryLists(true)
	local slot, list = self:GetClosestWidget(lists, self.active_slot:GetWorldPosition(), dir)
	if slot and list then		
		self.current_list = list
		return self:SelectSlot(slot)
	end
end





function Inventorybarcloneplayer:GetClosestWidget(lists, pos, dir)
	local closest = nil
	local closest_score = nil
	local closest_list = nil
	
	for kk, vv in pairs(lists) do
		for k,v in pairs(vv) do
			if v ~= self.active_slot then
				local world_pos = v:GetWorldPosition()
				local dst = pos:DistSq(world_pos)
				local local_dir = (world_pos - pos):GetNormalized()
				local dot = local_dir:Dot(dir)

				if dot > 0 then
					local score = dot/dst

					if not closest or score > closest_score then
						closest = v
						closest_score = score
						closest_list = vv
					end
				end
			end
		end
	end

	return closest, closest_list
end



function Inventorybarcloneplayer:GetCursorItem()
	return self.active_slot and self.active_slot.tile and self.active_slot.tile.item
end

function Inventorybarcloneplayer:OnControl(control, down)

end

function Inventorybarcloneplayer:OpenControllerInventory()
end

function Inventorybarcloneplayer:OnEnable()
	self:UpdateCursor()
end

function Inventorybarcloneplayer:OnDisable()
	self.actionstring:Hide()
end

function Inventorybarcloneplayer:CloseControllerInventory()
	if self.open then
		self.open = false
		SetPause(false)
		self.owner.HUD.controls:SetDark(false)
		self.owner.components.inventory:ReturnActiveItem()
		
		self:UpdateCursor()

		if self.active_slot then
			self.active_slot:DeHighlight()
		end

		self:ScaleTo(self.selected_scale, self.base_scale,.1)

		local bp = self.owner.HUD:GetFirstOpenContainerWidget()
		if bp and bp.scalewithinventory then
			self.owner.HUD:GetFirstOpenContainerWidget():ScaleTo(self.selected_scale,self.base_scale,.1)
		end

		TheFrontEnd:LockFocus(false)
	end
end

function Inventorybarcloneplayer:GetDescriptionString(item,emptyslot)
--	if emptyslot and emptyslot==true then return "emptyslot" end
    local str = nil
    local in_equip_slot = item and item.components.equippable and item.components.equippable:IsEquipped()
    local slot = self.owner.components.playercontroller_3.spitemnun or 1
	local active_item = self.owner.components.inventory:GetItemInSlot(slot)
    if item and item.components.inventoryitem then
        local adjective = item:GetAdjective()
        if adjective then
            str = adjective .. " " .. item:GetDisplayName()
        else
            str = item:GetDisplayName()
        end
    end
    
    return str or ""
end

function Inventorybarcloneplayer:IsWet(item)
	if self.owner.components.moisture then
		local MoistureManager = GetWorld().components.moisturemanager
		return MoistureManager and MoistureManager:IsEntityWet(item)
	else
		return false
	end
end

function Inventorybarcloneplayer:SetTooltipColour(r,g,b,a)
	self.actionstringtitle:SetColour(r,g,b,a)
end

function Inventorybarcloneplayer:UpdateCursorText()
	local W = self.w
	local SEP = self.sep
	local YSEP = self.ysep
	local INTERSEP = self.intersep	


	local inv_item = self:GetCursorItem()
	local active_item = self.cursortile and self.cursortile.item 
	local item = active_item or inv_item
	
	local emptyslot=false
	local spitenum =self.owner.components.playercontroller_3.spitemnun or 1
	local spiteitem = self.owner.components.inventory:GetItemInSlot(spitenum)
	if not spiteitem then

		emptyslot=true
	end
	

	if item then
		local itemname = self:GetDescriptionString(item,emptyslot)
		self.actionstringtitle:SetString(itemname)
    	if self:IsWet(item) then
        	self:SetTooltipColour(self.wet_text_colour[1], self.wet_text_colour[2], self.wet_text_colour[3], self.wet_text_colour[4])
    	else
        	self:SetTooltipColour(self.normal_text_colour[1], self.normal_text_colour[2], self.normal_text_colour[3], self.normal_text_colour[4])
	    end

	    local is_equip_slot = self.active_slot and self.active_slot.equipslot
	    local str = {}
	    
		local hasdroptag = self.owner:HasTag("dropinv")
		--local basestring =
		if emptyslot==false then
		
			if hasdroptag then
				print("")
				table.insert(str, self.actbutton.." - Drop / Cook / Add fuel / Put into chest")
			else
				table.insert(str, self.actbutton.." - Equip / Eat / Use")
				table.insert(str, "+"..self.altactbutton.." - drop / cook / add fuel / put into chest")

			end
		else
			table.insert(str, "")
		end
		
		
	    local was_shown = self.actionstring.shown
	    local old_string = self.actionstringbody:GetString()
	    local new_string = table.concat(str, '\n')
		
		
		
		
		
	local spitenum =self.owner.components.playercontroller_3.spitemnun or 1
	local spiteitem = self.owner.components.inventory:GetItemInSlot(spitenum)


		if spiteitem then
			self.actionstring:Show()
		else
			self.actionstring:Hide()
		end

	
	    if old_string ~= new_string then
		    self.actionstringbody:SetString(new_string)
		    self.actionstringtime = CURSOR_STRING_DELAY

		end


		local w0, h0 = self.actionstringtitle:GetRegionSize()
		local w1, h1 = self.actionstringbody:GetRegionSize()

		local wmax = math.max(w0, w1)

		local dest_pos = self.active_slot:GetWorldPosition()

		local yscale = self.root:GetScale().y
		local xscale = self.root:GetScale().x

		
		local actstring_y = 0
		local actstring_x = 0
		if self.plnum == 2 then
			actstring_y = -35
		else
			actstring_x = -35
		end
		
		if self.active_slot.side_align_tip then
			-- in-game containers, chests, fridge
			self.actionstringtitle:SetPosition(wmax/2+actstring_x, h0/2+actstring_y)
			self.actionstringbody:SetPosition(wmax/2+actstring_x, -h1/2+actstring_y)

			dest_pos = dest_pos + Vector3(self.active_slot.side_align_tip * xscale, 0, 0)
		elseif self.active_slot.top_align_tip then
			-- main inventory
			self.actionstringtitle:SetPosition(0+actstring_x, h0/2 + h1+actstring_y)
			self.actionstringbody:SetPosition(0+actstring_x, h1/2+actstring_y)

			dest_pos = dest_pos + Vector3(0, -(self.active_slot.top_align_tip + TIP_YFUDGE) * yscale+actstring_y, 0)
		else
			-- old default as fallback ?
			self.actionstringtitle:SetPosition(0, h0/2 + h1+actstring_y)
			self.actionstringbody:SetPosition(0, h1/2+actstring_y)

			dest_pos = dest_pos + Vector3(0+actstring_x, -(W/2 + TIP_YFUDGE) * yscale+actstring_y, 0)
		end



		if dest_pos:DistSq(self.actionstring:GetPosition()) > 1 then
			self.actionstringtime = CURSOR_STRING_DELAY
			if was_shown then
				self.actionstring:MoveTo(self.actionstring:GetPosition(), dest_pos, .1)
			else
				self.actionstring:SetPosition(dest_pos)
				self.actionstring:Show()
			end
		end
		
		
		
		
		end
end


function Inventorybarcloneplayer:SlotFromPC()

	local newslot = self.owner.components.playercontroller_3.spitemnun or 1
	local slotitem = self.inv[newslot]
	if newslot ==17 then
		slotitem = self.equip[EQUIPSLOTS.HANDS]
	elseif newslot ==18 then
		slotitem = self.equip[EQUIPSLOTS.BODY]
	elseif newslot ==19 then
		slotitem = self.equip[EQUIPSLOTS.HEAD]
	end
	self:SelectSlot(slotitem)



	return self.inv[newslot]
end

function Inventorybarcloneplayer:SelectSlotFromPC()

	local slot = self:SlotFromPC()
	self:SelectSlot(slot)

end



function Inventorybarcloneplayer:SelectSlot(slot)
	if slot and slot ~= self.active_slot then
		local newslot = slot or self.inv[1]
		if self.active_slot and self.active_slot ~= newslot then
			self.active_slot:DeHighlight()
		end
		
		self.active_slot = newslot
		self.active_slot:Highlight()
		return true
	end
end

function Inventorybarcloneplayer:UpdateCursor()


	if not self.active_slot then
		self:SelectSlotFromPC()
	end


	if self.active_slot and self.cursortile	then
		self.cursortile:SetPosition(self.active_slot:GetWorldPosition())
	end

	if self.active_slot then
	
		if self.cursor then
			self.cursor:Kill()
			self.cursor = nil
		end

		if not self.cursor then
			self.cursor = self.root:AddChild(Image( HUD_ATLAS, "slot_select.tex"))
			
		end
	
		if self.active_slot.tile and self.active_slot.tile:HasSpoilage() then
			self.cursor:Show()
			self.active_slot.tile:AddChild(self.cursor)
			self.active_slot:Highlight()

			self.cursor:MoveToBack()
			self.active_slot.tile.spoilage:MoveToBack()
			self.active_slot.tile.bg:MoveToBack()
		else
			self.cursor:Show()
			self.active_slot:AddChild(self.cursor)
			self.active_slot:Highlight()

			self.cursor:MoveToBack()
			self.active_slot.bgimage:MoveToBack()
		end
	else
		self.cursor:Hide()
	end
	


	if not self.owner.components.playercontroller_3 then return end
	local slot = self.owner.components.playercontroller_3.spitemnun or 1
	local active_item = self:SelectSlotFromPC()----//////
	if active_item then
		
		 if not self.cursortile or active_item ~= self.cursortile.item then
			
			 if self.cursortile then
				 self.cursortile:Kill()
			 end
			
			 self.cursortile = self.root:AddChild(ItemTile(active_item))
			 self.cursortile.image:SetScale(1.15)
			 self.cursortile:SetScaleMode(SCALEMODE_PROPORTIONAL)
			 self.cursortile:StartDrag()
			 self.cursortile:SetPosition(self.active_slot:GetWorldPosition())
		 end
	else
		 if self.cursortile then
			 self.cursortile:Kill()
			 self.cursortile = nil
		 end
	end
	self:UpdateCursorText()


end

function Inventorybarcloneplayer:Refresh()
	
	for k,v in pairs(self.inv) do
		v:SetTile(nil)
	end

	for k,v in pairs(self.equip) do
		v:SetTile(nil)
	end

	for k,v in pairs(self.owner.components.inventory.itemslots) do
		if v then
			local tile = ItemTile(v)
			self.inv[k]:SetTile(tile)
		end
	end

	for k,v in pairs(self.owner.components.inventory.equipslots) do
		if v then
			local tile = ItemTile(v)
			self.equip[k]:SetTile(tile)
		end
	end
	
	self:OnNewActiveItem(self:SelectSlotFromPC())

end


function Inventorybarcloneplayer:Cancel()
    local active_item = self:SelectSlotFromPC()
    if active_item then
        self.owner.components.inventory:ReturnActiveItem()
    end
end

function Inventorybarcloneplayer:OnItemLose(slot)
	if slot then
		slot:SetTile(nil)
	end
	
	--self:UpdateCursor()
end

function Inventorybarcloneplayer:OnBuild()
    if self.hovertile then
        self.hovertile:ScaleTo(3, 1, .5)
    end
end

function Inventorybarcloneplayer:OnNewActiveItem(item)
    
    if self.hovertile then
        self.hovertile:Kill()
        self.hovertile = nil
    end



end

function Inventorybarcloneplayer:OnItemGet(item, slot, source_pos)
    if slot  then
		local tile = ItemTile(item)
        slot:SetTile(tile)
        tile:Hide()

        if source_pos then
			local dest_pos = slot:GetWorldPosition()
			local im = Image(item.components.inventoryitem:GetAtlas(), item.components.inventoryitem:GetImage())
			im:MoveTo(source_pos, dest_pos, .3, function() tile:Show() tile:ScaleTo(2, 1, .25) im:Kill() end)
        else
			tile:Show() 
			--tile:ScaleTo(2, 1, .25)
        end
	end
end

function Inventorybarcloneplayer:OnItemEquip(item, slot)
    self.equip[slot]:SetTile(ItemTile(item))
	
	if self.hovertile then
        self.hovertile:Kill()
        self.hovertile = nil
    end
	
	self.active_slot = nil
	self:SelectSlotFromPC()
	self:UpdateCursor()
	
end

function Inventorybarcloneplayer:OnItemUnequip(item, slot)
    if slot and self.equip[slot] then
		self.equip[slot]:SetTile(nil)
		
	if self.hovertile then
        self.hovertile:Kill()
        self.hovertile = nil
    end
	
	self.active_slot = nil
	self:SelectSlotFromPC()
	self:UpdateCursor()
	end
end

return Inventorybarcloneplayer
