-- Inventory

Inventory = {}
Inventory.mElemParents = {}
Inventory.mElems = {}

function addInvLayer(name)
    local layer = render_layer:new(name)
    layer:get_parent():init()
    return layer
end

Inventory.mItemLayers =
{
    addInvLayer("LocSupplyClosetInv"),
    addInvLayer("LocKitchenInv"),
    addInvLayer("LocCourtyardInv"),
    addInvLayer("LocCoffeshopInv"),
    addInvLayer("LocValetParkingInv"),
    addInvLayer("LocGymInv"),
    addInvLayer("LocConciergeDeskInv"),
    addInvLayer("LocMailRoomInv"),
    addInvLayer("LocBeautySPAInv"),
    addInvLayer("LocSecurityStationInv"),
    addInvLayer("LocTailorInv"),
    addInvLayer("LocLaundryInv"),
    addInvLayer("LocSwimmingPoolInv"),
    addInvLayer("LocValetParkingCloseUpInv"),
    addInvLayer("LocWinterGardenInv"),
    addInvLayer("LocObservationDeckInv"),
    addInvLayer("LocManagersOfficeInv"),
    addInvLayer("LocExecutiveWashroomInv"),
    addInvLayer("LocConferenceRoomInv"),
    addInvLayer("LocPrivateRoomInv"),
    addInvLayer("LocNightClubInv")
}

local ITEM_STATE_PANEL = "panel"
local ITEM_STATE_CURSOR = "cursor"
local ITEM_STATE_SILHOUETTE = "silhouette"

local free = 0
local busy = 1

Inventory.mNumSlots = 3
Inventory.mSlots = {}

Inventory.mIsLocked = false

----------------------------------------------------------------------------------------------------
function Inventory:init()
    for i = 1, Inventory.mNumSlots do
        local slot = i
        Inventory.mSlots[slot] = free
        Panel:set_element_eh("inventory_anchor_"..slot, function() Inventory:slotClick(slot) end)
    end
end

function Inventory:slotClick(aSlot)

    if HODialogs:isVisible() or Inventory.mIsLocked or HOLevel.locked then
        return
    end

    local mouseElement = mouse:getConnectedName()

    local tItemName = nil
    table.foreach(Inventory.mElems,
        function(aName)
            if Inventory.mElems[aName].slot == aSlot then
                tItemName = aName
                return
            end
        end)

    if tItemName ~= nil and Inventory.mElems[tItemName].state == ITEM_STATE_SILHOUETTE then
        return
    end

    if Inventory.mSlots[aSlot] == free then
        -- слот свободен, на курсоре ничего нет. выходим
        if mouseElement == "" then
            return
        end

        -- слот свободен, на курсоре есть элемент. сбрасываем элемент в слот
        Inventory.mSlots[Inventory.mElems[mouseElement].slot] = free
        Inventory.mSlots[aSlot] = busy

        Inventory.mElems[mouseElement].slot = aSlot
        mouse:setConnCharacter(nil)
        Inventory.mElems[mouseElement].elem:setParent(Panel:get_parent():getElement("inventory_anchor_"..aSlot):getCharacter())
        Inventory.mElems[mouseElement].elem:setPos(Vec2(0, 0))
        Inventory:setItemState(mouseElement, ITEM_STATE_PANEL)

    else

        if tItemName == nil then
            trace("Inventory ACHTUNG!")
            return
        end

        -- слот занят, на курсоре ничего нет. поднимаем элемент из слота
        if mouseElement == "" then
            mouse:setConnCharacter(Inventory.mElems[tItemName].elem:getCharacter())
            Inventory:setItemState(tItemName, ITEM_STATE_CURSOR)

        -- слот занят, на курсоре есть элемент. если это "свой" элемент, сбрасываем элемент в слот, иначе ничего не делаем
        elseif Inventory.mElems[tItemName].slot == aSlot then
            mouse:setConnCharacter(nil)
            Inventory:setItemState(tItemName, ITEM_STATE_PANEL)
        end
    end
    
end

----------------------------------------------------------------------------------------------------
function Inventory:getFistFreeSlot()
    for i = 1, #Inventory.mSlots do
        if Inventory.mSlots[i] == free then
            return i
        end
    end

    return 0
end

----------------------------------------------------------------------------------------------------
function Inventory:dropElement()

    local mouseElement = mouse:getConnectedName()
    if mouseElement ~= "" then
        Inventory:setItemState(mouseElement, ITEM_STATE_PANEL)
    end

    mouse:setConnCharacter(nil)
end

----------------------------------------------------------------------------------------------------
function Inventory:pickElement(aSlot)
    local elemName = mouse:getConnectedName()

    if elemName ~= "" then
        return
    end

    local aItemName = nil
    table.foreach(Inventory.mElems,
        function(aName)
            if Inventory.mElems[aName].slot == aSlot then
                aItemName = aName
            end
        end)

    if aItemName == nil then
        return
    end

	local elem = Inventory.mElems[aItemName].elem
	if elem ~= nil then
		mouse:setConnCharacter(elem:getCharacter())
		play_clip(elem:getCharacter())
	end
end

----------------------------------------------------------------------------------------------------
function Inventory:addItem(aItemName)

    if Inventory.mElems[aItemName] ~= nil then
        return Inventory.mElems[aItemName].slot
    end

    local tSlot = Inventory:getFistFreeSlot()
    if tSlot == 0 then
        trace("Inventory full")
        return 0
    end

    tElem = nil
    for i = 1, #Inventory.mItemLayers do
        tElem = Inventory.mItemLayers[i]:get_element(aItemName)
        if tElem ~= nil then
            break
        end
    end

    if tElem == nil then
        trace("Inventory item "..aItemName.." not found")
        return 0
    end

    Inventory.mElemParents[aItemName] = tElem:getParent()
    tElem:setParent(Panel:get_parent():getElement("inventory_anchor_"..tSlot):getCharacter())

    --Panel:get_parent():getElement("inventory_anchor_"..tSlot)

    Inventory.mSlots[tSlot] = busy
    tElem:setActive(true)
    tElem:setPos(Vec2(0,0))

    Inventory.mElems[aItemName] = { elem = tElem, slot = tSlot }
    Inventory:setItemState(aItemName, ITEM_STATE_SILHOUETTE)

    return tSlot
end

----------------------------------------------------------------------------------------------------
function Inventory:setItemState(aItemName, aState)
    local tElem = Inventory.mElems[aItemName].elem

    if tElem ~= nil then
        Inventory.mElems[aItemName].state = aState

        play_clip(tElem:getCharacter(), {label_begin = aState, label_end = "stop_"..aState})

        --play_clip(tElem:getCharacter(), {label_begin = "panel", label_end = "stop_panel"})
        --if aState == ITEM_STATE_SILHOUETTE then
            --play_clip(tElem:getCharacter(), {label_begin = ITEM_STATE_SILHOUETTE, label_end = "stop_"..ITEM_STATE_SILHOUETTE})
        --end
    end
end

----------------------------------------------------------------------------------------------------
function Inventory:activateItem(aItemName)
    local tItem = Inventory.mElems[aItemName]

    if tItem == nil then
        return -1
    end

    Inventory:setItemState(aItemName, ITEM_STATE_PANEL)
    return tItem.slot
end

----------------------------------------------------------------------------------------------------
function Inventory:removeItem(aItemName)

    if Inventory.mElems[aItemName] == nil then
        return
    end

    Inventory.mSlots[Inventory.mElems[aItemName].slot] = free
    elem = Inventory.mElems[aItemName].elem

    Inventory.mElems[aItemName] = nil
    elem:setEventHandler(eiLeftClick, "")
    elem:setActive(false)
    elem:setParent(Inventory.mElemParents[aItemName])
    Inventory.mElemParents[aItemName] = nil

    elem:setPos(Vec2(-2000,-2000))
end

----------------------------------------------------------------------------------------------------
function Inventory:activateSlot(aSlot, aState)
    local slotElem = Panel:get_element("inventory_anchor_"..aSlot)

    if slotElem ~= nil then
        slotElem:setActive(aState)
    end
end

----------------------------------------------------------------------------------------------------
function Inventory:showSlotItem(aSlot, aState)

    local tItemName = nil
    table.foreach(Inventory.mElems,
        function(aName)
            if Inventory.mElems[aName].slot == aSlot then
                tItemName = aName
            end
        end)

    if tItemName ~= nil and Inventory.mElems[tItemName] ~= nil then
        Inventory.mElems[tItemName].elem:setVisible(aState)
    end
end

----------------------------------------------------------------------------------------------------
function Inventory:lock(aState)
    Inventory.mIsLocked = aState
end

----------------------------------------------------------------------------------------------------
function Inventory:clear()
    table.foreach(Inventory.mElems,
        function(aName)
            Inventory:removeItem(aName)
        end)
end

----------------------------------------------------------------------------------------------------
function Inventory:get(aName)
    if Inventory.mElems[aName] ~= nil and Inventory.mElems[aName].elem:isActive() then
        return Inventory.mElems[aName].elem
    end

    return nil
end

----------------------------------------------------------------------------------------------------
function Inventory:isPlaced(aName)
    if Inventory.mElems[aName] ~= nil and Panel:get_element("inventory_anchor_"..Inventory.mElems[aName].slot):isActive() then
        return true
    end

    return false
end

----------------------------------------------------------------------------------------------------
function Inventory:getList()
    local result = {}

    table.foreach(Inventory.mElems,
        function(aName)
            table.insert(result, {name = aName, state = Inventory.mElems[aName].state})
        end)

    return result
end
