-- plr is 'player'
-- item is the 'tool' or 'key' clicked on

function module.Clicked (plr, item)
    
    -- 1. Check is player exists (not nil) and player is not Piggy
    if plr then 
        if plr.Character and not plr:FindFirstChild("Piggy") then
            
            -- 2. Get the position of the part so we can swap parts
            -- models do not have position as a property, rather a PrimaryPart property which is generally the handle (some invisible part)
            
            local position
            if item:IsA("Model") then
                position = item.PrimaryPart.Position
            else
                position = item.Position
            end
            
            -- drop whatever is in the players backpack or equipped (if any)
            -- send in the player, the map and the position of the newly clicked item
            module.DropTools(plr, game.Workspace.Map, position)
            print ("Dropped Keyhandles")
            
            --3. Put a copy of the serverstorage item in the players backpack
            if game.ServerStorage.Tools:FindFirstChild(item.Name) then
                -- clone server copy
                local clonedTool = game.ServerStorage.Tools[item.Name]:Clone()
                
                -- put it in the players backpack
                clonedTool.Parent = plr.Backpack
                
                -- auto equip it
                plr.Character.Humanoid:EquipTool(clonedTool)
                
                -- destroy the part on the map
                item:Destroy()
                
                print ("Equipped the tool")
            end
            
        end        
    end
    
end

return module
