#####################################################################
#              WAREHOUSE MV EXPORTER / IMPORTER
#####################################################################

default buttonall = False
default cargospace = 0
default warehousespace = 0

label warehouse_multiverse_export():
    $ result = True

    # init data
    $ warehouseFileVersion = "WAREHOUSE_VERSION_100"

    # compile items list 
    $ warehouseItemData = [x.ID for x in GAME.base.wares if x.kind in ["module", "ware", "subunit", "subsys", "crate", "pod"] if x.ID not in ["ITMContainerBot"]] # CR-0755  
    $ warehouseItemData.sort()
    if warehouseItemData == []:
        queue sound "audio/tech_fail.wav"
        "Warehouse Manager" "\"You have no eligible wares stored here.\""
        return(False)

    $ warehouseItemData.append(hash(" ".join(warehouseItemData)))    

    # compile bots 
    $ warehouseBotData = []

    python:
        for qItem in GAME.base.storedGoods:
            bot = qItem[1]
            bFlatData = GAME.lab.dumpData(bot)      
            warehouseBotData.append(bFlatData)

    # create dump file
    $ warehouseFileData = [warehouseFileVersion, warehouseItemData, warehouseBotData]

    queue sound "audio/teleport.wav"
    scene room_tenaris_warehouse_smart with blueflash 
    scene room_tenaris_warehouse_smart with blueflash 
    "You watch a large part of your warehouse content and the pod shimmer and vanish..."
    mc "\"All those expensive parts, gone...\""
    mc "\"Let's hope I will see them again in another universe...\""

    # write out 
    python:
        with open(GAME.podDir + "/multiverse_warehouse.json", "w") as f:
            json.dump(warehouseFileData, f)            

    # wipe exported warehouse stuff

    python:
        # wipe exported items
        warehouseItemData.pop(-1) # remove hashed key
        for i in warehouseItemData:
            item = GAME.items[i]
            GAME.base.wares.remove(item)
        # wipe bots
        for qItem in [x for x in GAME.base.storedGoods]: # tokenized goods
            GAME.base.storedGoods.remove(qItem)
            GAME.base.wares.remove(GAME.items["ITMContainerBot"])

    # notify 
    queue sound "audio/notify.wav"
    call large_notify("SYSTEM INFORMATION", "Your warehouse content has been stored at {}. It will be automatically found in new games.\n\nBack it up elsewhere if you want multiple warehouse states to avoid overwrite.".format(GAME.podDir+"/multiverse_warehouse.json"),  ["Continue"], "08_items/ico ITMMultiPod.png", "orange") from _call_large_notify_78

    # remove pod
    $ GAME.mc.remItem("ITMMultiPod")
    $ GAME.tags.append("warehouse_sent")

    return(result)

label warehouse_multiverse_import():

    "As you enter the Warehouse, you notice a shimmer in the air..."
    queue sound "audio/teleport.wav"
    scene room_tenaris_warehouse_smart with blueflash
    scene room_tenaris_warehouse_smart with blueflash
    "From the Multiverse a number of items appears on the Warehouse shelves..."


    # read in multiverse items from file
    # ===== CR-0581 START
    # python:
    #     with open(GAME.podDir + "/multiverse_warehouse.json", "r") as f:
    #         warehouseFileData = json.load(f)
    $ warehouseFileData = GAME.mvWarehouseData
    # ===== CR-0581 END

    # ===== CR-0851 START
    if warehouseFileData:
        $ warehouseItems = []
        $ warehouseBots = []

        $ warehouseDataVersion = warehouseFileData[0]
        $ warehouseItemData = warehouseFileData[1]
        $ warehouseBotData = warehouseFileData[2]

        
        # reconstruct bots
        $ reconstructedBots = []
        python:
            for entry in [x for x in warehouseBotData]:
                bot = GAME.lab.reconstruct(entry, warehouseDataVersion)
                reconstructedBots.append(bot) 

        # retrieve cargo items 
        $ checksum = warehouseItemData[-1] 
        $ warehouseItemData = warehouseItemData[:-1]
        $ checksum2 = hash(" ".join(warehouseItemData))
        python:
            for entry in [x for x in warehouseItemData]:
                warehouseItems.append(GAME.items[entry])
        $ result = {"bots": 0, "items": 0}
        # ===== CR-0851 END

        # store away retrieved stuff
        while warehouseItems:
            $ item = warehouseItems.pop()
            $ GAME.base.wares.append(item) 
            $ result["items"]+= 1


        while reconstructedBots:
            $ bot = reconstructedBots.pop()
            # add bot
            $ GAME.base.storedGoods.append(["bot", bot, "Multiverse"])
            # add token 
            $ GAME.base.wares.append(GAME.items["ITMContainerBot"])
            $ result["bots"]+= 1

        queue sound "audio/notify.wav"
        call simple_notify("RECONSTRUCTION COMPLETE","Goods: {}x, Bots: {}x".format(result["items"], result["bots"]), ["Continue"], "08_items/ico ITMMultiPod.png") from _call_simple_notify_101
    
        mc "\"My stuff!\""
        mc "\"I really have to thank Ylyee one day...\""

    return(result)

#####################################################################
#              CARGO DRONE MANAGER
#####################################################################

screen cargo_drone_select():
    frame xsize 860 ysize 560 xalign 0.5 yalign 0.5 padding 20,20:    
        modal True
        # title
        # image "08_items/ico ITMDroneRemote.png" ypos -30 xalign 1.0 zoom 0.25

        text ACCENTS["blue"][0]+ "DRONE STATUS" +ACCENTS["blue"][1] xalign 0.5 ypos 10

        # contents
        vbox spacing 5 xalign 0.5 xsize 820 ypos 80:
            for drone in GAME.drones:
                frame xsize 820 ysize 60 background Solid ("#0099cc22"):
                    image "08_items/ico ITMDroneRemote.png" ypos -40 zoom 0.25
                    text "{}{}{}".format(C_OR_B,drone.ID.upper(), C_OR_E) size FSIZE yalign 0.5 xpos 140
                    $ cargo = ""
                    $ C_B , C_E = "", ""
                    if drone.status == "en route":
                        $ cargo = " / {}t".format(len(drone.cargo))
                        $ C_B, C_E = C_HI_B, C_HI_E 
                    elif drone.status == "standby":
                        $ C_B, C_E = C_GR_B, C_GR_E 
                    elif drone.status == "blocked":
                        $ C_B, C_E = C_RE_B, C_RE_E 
                    text "{}{}{}{}".format(C_B, drone.status.title(), cargo, C_E) size FSIZE xpos 280 yalign 0.5
                    text "{}".format(drone.dest.title()) size FSIZE yalign 0.5 xpos 460
 
                    # text "{}".format(drone.dueDate) size FSIZE xpos 450 xalign 1.0 yalign 0.5
 
                    if drone.dest == "ship" and drone.status == "standby":
                        frame xsize 80 ysize 30 background Solid ("#0099ccff") yalign 0.5 xpos 620:
                            text "Dispatch" xalign 0.5 yalign 0.5 size FSIZE_MED
                            button action Return(["dispatch",drone])                    
                    elif drone.dest == "warehouse" and drone.status == "standby":
                        frame xsize 80 ysize 30 background Solid ("#0099ccff") yalign 0.5 xpos 620:
                            text "Summon" xalign 0.5 yalign 0.5 size FSIZE_MED
                            button action Return(["summon",drone])       
                    else:
                        text "Arrival: Day {}".format(drone.dueDate) size FSIZE xpos 620 yalign 0.5            


        # buttons
        frame xsize 140 ysize 36 background Solid("#0099cc") yalign 0.95 xalign 0.5:
            text "Exit"  size FSIZE xalign 0.5
            button action Return("Exit")
            key "K_SPACE" action Return("Exit")

label cargo_drone_manager():
    # initialize 
    "You access the cargo drone status..."
    # cargo drone select
    $ loopDrone = True
    while loopDrone:
        call screen cargo_drone_select
        queue sound "audio/click.wav"
        # exit
        if _return == "Exit":
            queue sound "audio/beep.wav"
            return()
        elif GAME.ship.status == "landed" and GAME.getSpaceLoc().ID == "LIDTenaris":
            queue sound "audio/notify.wav"
            mc "\"I'm docked right next to my Warehouse.\""
            mc "\"I better manage my cargo directly from there...\""
        elif "summon" in _return:
            $ drone = _return[1]
            # load drone 
            $ loopLoad = True 
            while loopLoad:
                call screen item_shop_scr(drone.cargo, "DRONE LOAD", GAME.base.wares, "WAREHOUSE", (1.0,1.0), "drone" )
                queue sound "audio/click.wav"
                if _return == False:
                    queue sound "audio/load.wav"
                    "Drone launched from Warehouse..."
                    $ drone.send("ship", GAME.day+2)
                    $ loopLoad = False
                    
                elif "sell" in _return and len(drone.cargo) >= 10:
                    play sound "audio/tech_fail.wav"
                # CR-0824 START ===========
                elif _return[1].ID == "ITMContainerBot":
                    play sound "audio/tech_fail.wav"
                    "Cargo Manager" "\"Drones not configured for BOT transport.\""
                # CR-0824 END ==============
                elif "sell" in _return:
                    $ drone.cargo.append(_return[1])
                    $ GAME.base.wares.remove(_return[1])
                elif "buy" in _return:
                    $ drone.cargo.remove(_return[1])
                    $ GAME.base.wares.append(_return[1])
        elif "dispatch" in _return:
            $ drone = _return[1]
            # load drone 
            $ loopLoad = True 
            while loopLoad:
                call screen item_shop_scr(drone.cargo, "DRONE LOAD", GAME.ship.cargo, "SHIP CARGO", (1.0,1.0), "drone" )
                queue sound "audio/click.wav"
                if _return == False:
                    queue sound "audio/load.wav"
                    "Drone launched from ship..."
                    $ drone.dest = "warehouse"
                    $ drone.status = "en route"
                    $ drone.dueDate = GAME.day+2 
                    $ loopLoad = False
                elif "sell" in _return and len(drone.cargo) >= 10:
                    play sound "audio/tech_fail.wav"
                # CR-0824 START ===========
                elif _return[1].ID == "ITMContainerBot":
                    play sound "audio/tech_fail.wav"
                    "Cargo Manager" "\"Drones not configured for BOT transport.\""
                # CR-0824 END ==============
                elif "sell" in _return:
                    $ drone.cargo.append(_return[1])
                    $ GAME.ship.cargo.remove(_return[1])
                elif "buy" in _return:
                    $ drone.cargo.remove(_return[1])
                    $ GAME.ship.cargo.append(_return[1]) 
                    

    return()

#####################################################################
#                WAREHOUSE
#####################################################################
screen warehouse_manager_scr(*args):
    $ items = args[0]
    $ mode = args[1]
    $ iFilters = args[2]
    $ iFilter = args[3]
    $ stored = args[4] 
    $ sTitle = args[5] 
    $ yadj = args[6] # parts viewport manager y-pos
    $ autobuyFilter = args[7]

    $ colPos = [60, 320, 550, 630, 715, 740, 890, 1055, 1225, 1280, 1355, 1540]
    $ cargospace = str(GAME.ship.cargoFree()) + "t Free"
    $ warehousespace = str(GAME.base.capaMax - len(GAME.base.wares)) + "t Free"
    $ colName = ["ware", "legality", "value", "ship", "stores", " cargo hold\n  ", "  warehouse\n  ", "", "autostock"]

    # compile reserved contingent for missions 
    $ reserved = GAME.missionSys.getReserved()
    $ reserved2 = GAME.missionSys.getReserved2()

    # headline and headers
    #text C_HI_B+"{}\n      - ({:,} of {:,}t)".format(sTitle, len(GAME.base.wares), GAME.base.capaMax)+C_HI_E size FSIZE_LARGE xpos 25 ypos 100
    text C_HI_B+"{}\n      ({:,} of {:,}t)".format(sTitle, len(GAME.base.wares), GAME.base.capaMax)+C_HI_E size FSIZE_LARGE xpos 25 ypos 100
    # Filters
    hbox pos 465,83 spacing 20:
        for i in iFilters:
            if i == iFilter:
                frame xsize 180 ysize 40 background Solid("#0099cc88"):
                    text i.title() xalign 0.5 yalign 0.5 size FSIZE
                    button action Return(["filter", i])
            else:
                frame xsize 180 ysize 40 background Solid("#00000000"):
                    text i.title() xalign 0.5 yalign 0.5 size FSIZE
                    button action Return(["filter", i])
            if i != iFilters[-1]:
                text "|" size FSIZE yalign 0.5

    text cargospace xpos 1215 ypos 179 size 24 xalign 0.5
    text warehousespace xpos 1378 ypos 179 size 24 xalign 0.5

    frame pos 410,140 xsize 1420 ysize 64 background Solid("#0099cc88"):
        for x in range(len(colName)):
            if colName[x] in ["ship", "value", "stores"]:
                text colName[x].title() xalign 1.0 yalign 0.5 xpos colPos[x] size FSIZE yoffset 1
            else:
                text colName[x].title() yalign 0.5 xpos colPos[x] size FSIZE yoffset 1
    side "c r":
        area 410,219,1450,790
        viewport id "vp":
            draggable True
            mousewheel True
            yadjustment yadj

            # # wares and crates
            vbox xpos 40 ypos 200 spacing 6:

                for i in items:
                    if i.kind == iFilter:
                        frame xsize 1420 ysize 60 background Solid("#0099cc88"):
                            image "08_items/ico {}.png".format(i.ID) zoom 0.125 yalign 0.5 xpos -5
                            text i.name xpos colPos[0] yalign 0.5 size FSIZE
                            text "Tradeable" xpos colPos[1] yalign 0.5 size FSIZE

                            button action NullAction() tooltip i

                            # value
                            text "{:,}".format(i.price) xpos colPos[2] xalign 1.0 yalign 0.5 size FSIZE

                            # in cargo
                            $ amount = GAME.ship.cargo.count(i)
                            if amount:
                                text "{} x".format(GAME.ship.cargo.count(i)) xpos colPos[3] yalign 0.5 xalign 1.0 size FSIZE
                            else:
                                text "-" xpos colPos[3] xalign 1.0 yalign 0.5 size FSIZE

                            # stored
                            $ amount = GAME.base.wares.count(i)
                            if amount:
                                text "{} x".format(GAME.base.wares.count(i)) xpos colPos[4] yalign 0.5 xalign 1.0 size FSIZE
                            else:
                                text "-" xpos colPos[4] xalign 1.0 yalign 0.5 size FSIZE


                            # action buttons
                            # to ship 
                            #if mode == "single":
                                #$ b_ship, b_stock, b_scrap = "Load", "Store", "Scrap"
                            if mode == "5x":
                                $ b_ship, b_stock, b_scrap = "Load 5x", "Store 5x", "Scrap 5x"
                            if mode == "10x":
                                $ b_ship, b_stock, b_scrap = "Load 10x", "Store 10x", "Scrap 10x"
                            elif mode == "all":
                                $ b_ship, b_stock, b_scrap = "Load All", "Store All", "Scrap All"

                            if i in GAME.base.wares:
                                frame xsize 50 ysize 30 background Solid ("#0099ccff") yalign 0.5 xpos colPos[5]:
                                    text "Load" xalign 0.5 yalign 0.5 size FSIZE_MED
                                    button action (SetVariable("buttonall", False), Return(["ship",i]))
                                frame xsize 78 ysize 30 background Solid ("#0099ccff") yalign 0.5 xpos colPos[5] xoffset 55:
                                    text b_ship xalign 0.5 yalign 0.5 size FSIZE_MED
                                    button action (SetVariable("buttonall", True), Return(["ship",i]))

                            # to storage 
                            if i in GAME.ship.cargo and i.ID not in ["ITMContainerBot"]:
                                frame xsize 55 ysize 30 background Solid ("#0099ccff") yalign 0.5 xpos colPos[6]:
                                    text "Store" xalign 0.5 yalign 0.5 size FSIZE_MED
                                    button action (SetVariable("buttonall", False), Return(["stock",i]))
                                frame xsize 88 ysize 30 background Solid ("#0099ccff") yalign 0.5 xpos colPos[6] xoffset 60:
                                    text b_stock xalign 0.5 yalign 0.5 size FSIZE_MED
                                    button action (SetVariable("buttonall", True), Return(["stock",i]))

                            # to scrap 
                            if i in GAME.base.wares and i.ID not in ["ITMContainerBot"]:
                                frame xsize 60 ysize 30 background Solid ("#0099ccff") yalign 0.5 xpos colPos[7]:
                                    text "Scrap" xalign 0.5 yalign 0.5 size FSIZE_MED
                                    button action (SetVariable("buttonall", False), Return(["scrap",i]))     
                                frame xsize 87 ysize 30 background Solid ("#0099ccff") yalign 0.5 xpos colPos[7] xoffset 65:
                                    text b_scrap xalign 0.5 yalign 0.5 size FSIZE_MED
                                    button action (SetVariable("buttonall", True), Return(["scrap",i]))     

                            # autobuy
                            if GAME.base.hasConstructed("SEIDTenarisHangar") and i.ID in autobuyFilter: # Hangar bought
                                $ active = i.ID in GAME.base.autobuyActive.keys()  
                                if active:
                                    $ active = GAME.base.autobuyActive[i.ID]                             
                                frame xsize 50 ysize 30 background Solid ("#0099ccff") yalign 0.5 xpos colPos[8]:   
                                    text {True: "ON", False: "OFF"}[active] xalign 0.5 yalign 0.5 size FSIZE_MED
                                    button action Return(["auto",i])  
                                if active:
                                    frame xsize 50 ysize 30 background Solid ("#0099ccff") yalign 0.5 xpos colPos[9]: 
                                        text "{:,}".format(GAME.base.autobuyQuantity[i.ID]) xalign 0.5 yalign 0.5 size FSIZE_MED
                                        button action Return(["quantity",i]) 

                            # reserved contingent for missions 
                            if i.ID in reserved.keys():
                                if reserved[i.ID] > GAME.ship.cargo.count(i):

                                    if reserved[i.ID] == reserved2[i.ID]:
                                            text "{}({}){}".format(C_OR_B, reserved2[i.ID],C_OR_E) yalign 0.5 xpos colPos[10] size FSIZE

                                    elif reserved2[i.ID] > GAME.ship.cargo.count(i):
                                            text C_OR_B + "({})\n({})*".format(reserved2[i.ID], reserved[i.ID]) + C_OR_E ypos 0 xpos colPos[10] size FSIZE
                                    else:
                                            text "{}({}){}".format(C_YE_B,reserved2[i.ID],C_YE_E) ypos 0 xpos colPos[10] size FSIZE
                                            text "{}({})*{}".format(C_OR_B,reserved[i.ID],C_OR_E) ypos 27 xpos colPos[10] size FSIZE

                                else:
                                    if reserved[i.ID] == reserved2[i.ID]:
                                        text "{}({}){}".format(C_GR_B,reserved[i.ID],C_GR_E) yalign 0.5 xpos colPos[10] size FSIZE
                                    else:
                                        text "{}({})*{}".format(C_GR_B,reserved[i.ID],C_GR_E) yalign 0.5 xpos colPos[10] size FSIZE


        vbar value YScrollValue("vp") xoffset 10
    
    if reserved:
        text "[C_YE_B](x) = Reserved contingent for accepted mission (single sale only)[C_YE_E]" size FSIZE_MED xpos 1330 yalign 0.971
        text "[C_YE_B](x)* = Multiple contracts[C_YE_E]" size FSIZE_MED xpos 1330 yalign 0.995



    #####################################################################
    #                TOOLTIP
    #####################################################################
    $ tooltip = GetTooltip()
    if tooltip:
        frame padding 20,20 xsize 400 ysize 920 pos 30 , 200 background Solid("#39210000"):
            image "08_items/ico bg1.png" zoom 0.5 xpos 25 ypos 100
            image "08_items/ico {}.png".format(tooltip.ID) zoom 0.5 xpos 25 ypos 100
            vbox xsize 360 ypos 420 xpos -25 spacing 20:
                text tooltip.getName(["col", "cap", "noArt"]) xalign 0.5
                text tooltip.description xalign 0.5 size FSIZE
                text "Value: {:,} Cr".format(tooltip.price) xalign 0.5 size FSIZE

    text "A = Toggle 5x / 10x / All Mode" size FSIZE_MED xalign 0.9475 yalign 0.995


    #####################################################################
    #                EXIT BUTTON, KEYS, ...
    #####################################################################
    frame xsize 350 ysize 64 pos 0,980 background Solid("#00000000") padding 0,0:
        image "05_gui/gui_menu_option.png" yalign 0.5
        button action Return(["exit", None])
        textbutton "Exit (X)" yalign 0.5 action Return(["exit", None])xpos 20
        key "x" action Return(["exit", None])
        key "X" action Return(["exit", None])

    key "a" action Return (["mode"])

label warehouse_manager(mode = [], attr = {}):
    $ GAME.mc.hasDone("cargo")
    # background & scene
    $ sTitle = "WAREHOUSE"
    if "title" in attr.keys():
        $ sTitle = attr["title"]

    show image "05_gui/mask 50.png"
    show screen header()
    play sound "audio/beep.wav"

    # warehouse date / items
    if not sLoc:
        $ sLoc = GAME.getSpaceLoc()
    $ itemsWarehouse = set(GAME.base.wares)
    $ iFilters = ["ware", "crate", "subunit", "subsys", "module", "pod"]
    $ iFilter = "ware"
    $ autobuyFilter = [x.ID for x in GAME.items.values() if x.kind in ["ware", "module", "subunit", "pod"] and "no_find" not in x.tags]
    $ yadj = ui.adjustment() # to remember ypos in cargo lists

    # presort
    $ itemsShip = set(GAME.ship.cargo)
    $ sortedItems = list(itemsShip | itemsWarehouse)
    $ sortedItems.sort(key = lambda x : x.price, reverse=True)
    $ mode = "10x"
    #$ sortedItems.sort(key = lambda x : x in GAME.ship.cargo, reverse = True)

    # manager loop

    while True:
        $ itemsWarehouse = set(GAME.base.wares)
        $ itemsShip = set(GAME.ship.cargo)

        $ sortedItems = list(itemsShip | itemsWarehouse)
        $ sortedItems.sort(key = lambda x : x.price, reverse=True)

        call screen warehouse_manager_scr(sortedItems, mode, iFilters, iFilter, GAME.base.wares, sTitle, yadj, autobuyFilter)

        if "exit" in _return:
            play sound "audio/click.wav"
            hide image "05_gui/mask 50.png"
            return()

        elif "mode" in _return:
            queue sound "audio/click.wav"
            $ mode = {"5x": "10x", "10x": "all", "all": "5x"}[mode]

        elif "auto" in _return:
            queue sound "audio/click.wav"
            $ item = _return[1]
            if item.ID not in GAME.base.autobuyActive.keys():
                $ GAME.base.autobuyActive[item.ID] = False  
                $ GAME.base.autobuyQuantity[item.ID] = 1
            $ GAME.base.autobuyActive[item.ID] =  not GAME.base.autobuyActive[item.ID]    

        elif "filter" in _return:
            $ iFilter = _return[1]
            play sound "audio/click.wav"

        elif "quantity" in _return:
            queue sound "audio/click.wav"
            $ item = _return[1]     
            $ qtyCurrent = GAME.base.autobuyQuantity[item.ID] 
            $ qtyNew = {0:1, 1:5, 5:10, 10:25, 25:50, 50:100, 100:200, 200:500, 500:0}[qtyCurrent]
            $ GAME.base.autobuyQuantity[item.ID] = qtyNew

        elif "ship" in _return:
            $ item = _return[1]
            if item.ID == "ITMContainerBot":
                # remove from tokenized warehouse queue
                $ qItem = GAME.base.storedGoods[0] # first bot in tokenized queue ref
                $ bot = qItem[1]
                $ botTag = qItem[2]
                # load to ship
                $ GAME.base.loadBot(bot) #xxx
                queue sound "audio/load.wav"
                call simple_notify("WAREHOUSE INFO", "[C_HI_B][bot.name][C_HI_E] moved to cargo", ["Continue"], "08_items/ico ITMContainerBot.png") from _call_simple_notify_102

            else:
                $ qty = 1 
                if buttonall:
                    $ qty = min(GAME.ship.cargoFree(), GAME.base.wares.count(item))
                    if mode == "5x" and qty > 5:
                        $ qty = 5
                    elif mode == "10x" and qty > 10:
                        $ qty = 10
                python:
                    transaction = False
                    while qty:
                        qty -= 1
                        if GAME.ship.cargoFree():
                            GAME.ship.cargo.append(item)
                            GAME.base.wares.remove(item)
                            transaction = True
                if transaction and buttonall:
                    queue sound "audio/load.wav"
                elif transaction and not buttonall:
                    queue sound "audio/click.wav"
                else:
                    queue sound "audio/tech_fail.wav"

        elif "stock" in _return:
            $ item = _return[1]
            $ qty = 1
            if buttonall:
                $ qty = min(GAME.base.capaMax-len(GAME.base.wares), GAME.ship.cargo.count(item))
                if mode == "5x" and qty > 5:
                    $ qty = 5
                elif mode == "10x" and qty > 10:
                    $ qty = 10
            python:
                transaction = False
                while qty:
                    qty -= 1
                    if len(GAME.base.wares)< GAME.base.capaMax:
                        GAME.ship.cargo.remove(item)
                        GAME.base.wares.append(item)
                        transaction = True
            if transaction and buttonall:
                queue sound "audio/load.wav"
            elif transaction and not buttonall:
                queue sound "audio/click.wav"
            else:
                queue sound "audio/tech_fail.wav"

        elif "scrap" in _return:
            $ item = _return[1]
            $ qty = 1 
            if buttonall:
                $ qty = GAME.base.wares.count(item)
                if mode == "5x" and qty > 5:
                    $ qty = 5
                elif mode == "10x" and qty > 10:
                    $ qty = 10
            while qty:
                $ qty -= 1
                $ GAME.base.wares.remove(item)
            queue sound "audio/coin.wav"
            call transaction("Scrap Proceeds", int(item.price/2.0), True) from _call_transaction_42


        # elif "buy all" in _return:
        #     $ b_item = _return[1] 
        #     $ purchase = False
        #     while b_item in sLoc.wares and GAME.money > sLoc.getPrice(b_item, "buy") and GAME.ship.cargoFree():
        #         $ purchase = True
        #         $ GAME.ship.cargo.append(b_item)
        #         $ sLoc.wares.remove(b_item)
        #         call transaction("Wares Bought", -sLoc.getPrice(b_item, "buy"), False)
        #     if purchase:
        #         queue sound "audio/coin.wav"


        else:
            play sound "audio/click.wav"

    return()


    if GAME.ship.cargoFree() <= 0:
        return()
    # process incoming item 
    $ processing = True
    $ GAME.inQueuePending.sort(key = lambda x : x[2]) # arrival day sort
    while GAME.ship.cargoFree() and GAME.inQueuePending and processing:
        if GAME.inQueuePending[0][2] > GAME.day:
            $ processing = False
        else:
            $ qItem = GAME.inQueuePending.pop(0)
            $ item = qItem[1]
            $ kind = qItem[0]
            if kind == "bot":
                queue sound "audio/notify.wav"
                call large_notify("DELIVERY DRONE", "A bot stasis pod containing {0} has been returned from the arcade to your ship via a delivery drone as requested.\n\n{0} can be retrieved from her stasis pod in the cargo bay.".format(C_SU_B+item.name+C_SU_E), ["Continue"], "03_minigames/ico_BotArcade.png", "orange") from _call_large_notify_79
                queue sound "audio/install.wav"
                # align unpacking token item with bot queue list
                $ GAME.ship.packBot(item, "Arcade Return")  
            else:
                "Delivery queue processing issue: Unknow Entity '[kind]'"
                "Entity has been purged from queue. It is safe to continue."
    return()