#####################################################################
#                MG MAINTENANCE
#####################################################################
init:
    transform customzoom:
        zoom 0.15
screen mg_maintenance_scr(*args):
    $ subSysKey = args[0]
    $ cRows = [0, 120, 240]
    $ cCols = [0, 110, 220, 330]
    $ subunits = ["ITMAICore", "ITMPositron", "ITMFlux", "ITMOutput"]

    text C_HI_B+"SYSTEM MAINTENANCE"+C_HI_E size FSIZE_LARGE xpos 20 ypos 85
    $ subSys = GAME.ship.subSys[subSysKey]


    hbox xpos 812 ypos 355 spacing 35:
        $ subunits2 = ["ITMAICore", "ITMPositron", "ITMFlux", "ITMOutput"]
        for i in subunits2:
            text "{} in cargo".format(GAME.ship.cargo.count(GAME.items[i])) yalign 0.5 size 20 color "#0CF"
        
    text "{} Tunneling\nModules\nin cargo".format(GAME.ship.cargo.count(GAME.items["ITMTunneling"])) xpos 1286 ypos 354 line_spacing -2 text_align 1.0 size 19 color "#0CF"

    #####################################################################
    #                COMPONENT SELECTION
    #####################################################################
    if subSys[0]:
        $ item = GAME.items[subSys[0]]
        frame xsize 372 ysize 372 pos 230, 356 background Solid ("#00000000"):
            image "08_items/ico bg1.png" xalign 0.5 yalign 0.5 zoom 0.7
            image "08_items/ico {}.png".format(item.ID)  xalign 0.5 yalign 0.5 zoom 0.7
        #image "03_minigames/item_{}_512x372.png".format(subSysKey) pos 172, 356
        vbox xsize 452 pos 172, 699 spacing 25:
            text "{}".format(GAME.items[subSys[0]].getName(["noArt", "cap", "col"])) #size FSIZE
            text "{}".format(GAME.items[subSys[0]].description) size FSIZE
 
        #####################################################################
        #					GENERAL LOADOUT		
        #####################################################################
        if GAME.ship.supportsAddOns(subSysKey):
            $ maxLoadout = GAME.ship.getLoadoutMax(subSysKey)
            $ addOns = GAME.ship.getAddOns(subSysKey)
            vbox pos 620, 376 spacing 10:
                for i in range(6):
                    if maxLoadout >= i+1:
                        frame xsize 48 ysize 48 background Solid("#00000000"):
                            image "03_minigames/ico_slot_subunit.png" xalign 0.5 yalign 0.5 zoom 0.5
                            if addOns[i]:
                                image "08_items/ico {}.png".format(addOns[i].ID) xalign 0.5 yalign 0.5 zoom 0.175
                            button action Return(["addon", subSysKey, i, addOns[i]])
                    else:
                        frame xsize 48 ysize 48 background Solid("#00000000"):
                            text "-" xalign 0.5 yalign 0.5

    else:
        text "NOT INSTALLED" pos 438, 542 xalign 0.5

    
    hbox pos 172, 280 spacing 20:
        #imagebutton hover "05_gui/gui arrow left.png" idle "05_gui/gui arrow left.png" action Return(["left"])
        frame xsize 100 ysize 40 yalign 0.5 background Solid("#0099ccff"):
            text "PREV" size FSIZE xalign 0.5 ypos 5
            button action Return(["left"])
        hbox xsize 270 yalign 0.5:
            text subSysKey.upper() xalign 0.5 yalign 0.5
        frame xsize 100 ysize 40 yalign 0.5 background Solid("#0099ccff"):
            text "NEXT" size FSIZE xalign 0.5 ypos 5
            button action Return(["right"])
    key "K_LEFT" action Return(["left"])
    key "K_RIGHT" action Return(["right"])

    frame xsize 660 ysize 70 pos 390, 210 xalign 0.5 yalign 0.5 background Solid ("#0000FF50"):
      hbox pos 345,10 spacing 50:
        $ x = len(subSystems)
        for i2 in range(0, x):
            $ y = (subSystems[i2])
            if GAME.ship.hasSubSys(y):
                $ y1 = GAME.ship.getSubSys(y)
            $ item1 = GAME.items[(y1)]
            fixed xsize 30 ysize 30:# background Solid ("#00000000"):
                if i2 % 2 == 1:
                  $ xoff_spacing = (i2 * -45) - 350
                else:
                  $ xoff_spacing = (i2 * -45) + 40

                if i2 == 0:
                    image "08_items/ico bg1.png" xalign 0.5 yalign 0.5 zoom 0.25
                    image "08_items/ico {}.png".format(item1.ID)  xalign 0.5 yalign 0.5 zoom 0.25
                else:
                    imagebutton idle "08_items/ico {}.png".format(item1.ID):
                        xalign 0.5 
                        yalign 0.5 
                        xoffset xoff_spacing
                        action Return(["systype", y])
                        at customzoom
                    if GAME.ship.supportsAddOns(subSystems[i2]):
                        $ addOns2 = GAME.ship.getAddOns(subSystems[i2])
                        $ maxLoadout2 = GAME.ship.getLoadoutMax(subSystems[i2])
                        $addoncount = 0
                        for i in range(6):
                            if addOns2[i] :
                                $addoncount += 1
                        #$ addoncounttext = str(addoncount) + "of" + str(maxLoadout2)
                        fixed:
                            text str(addoncount) + "{size=18}of{/size}" + str(maxLoadout2) xalign 1.0 ypos -35 xoffset xoff_spacing size 24 color "#0FF"
                    $ sys_eff = str(int(GAME.ship.getSubSysStatus(subSystems[i2])))
                    text sys_eff + "%" xalign 0.5 ypos 50 xoffset xoff_spacing size FSIZE color "#0FF"

    text "____" xpos 715 ypos 137 size 32 color "09F" bold True kerning -10
    text "Subunits" xpos 770 ypos 155 size 24 color "#999"
    text "____" xpos 715 ypos 224 size 32 color "09F" bold True kerning -10
    text "Efficiency" xpos 770 ypos 242 size 24 color "#999"

    

    #####################################################################
    #                SUBUNITS
    #####################################################################
    for j in range(3):
        for i in range(4):
            # draw connection line:
            if i == 0:
                if GAME.ship.pathClosed(subSysKey, j):
                    image "connection_active" xpos 780+cCols[i]+64 ypos 350+cRows[j]+62
                else:
                    image "05_gui/mgm_inactive_line.png" xpos 780+cCols[i]+64 ypos 350+cRows[j]+62
            # draw subunits
            if subSys[j+1][i] == 1:
                frame xsize 80 ysize 80 pos 780+cCols[i]+32, 350+cRows[j]+34 background Solid("#ffffff00"):
                    image "03_minigames/ico_slot_subunit.png" xalign 0.5 yalign 0.5
                    image "08_items/ico {}.png".format(subunits[i]) zoom 0.25 xalign 0.5 yalign 0.5
                    button action Return([ "subunit", subunits[i], [j,i] ]) tooltip subunits[i]
            elif subSys[j+1][i] == 9:
                frame xsize 80 ysize 80 pos 780+cCols[i]+32, 350+cRows[j]+34 background Solid("#ffffff00"):
                    image "03_minigames/ico_slot_subunit.png" xalign 0.5 yalign 0.5
                    image "08_items/ico {}.png".format("ITMTunneling") zoom 0.25 xalign 0.5 yalign 0.5

                    button action Return([ "subunit", "ITMTunneling", [j,i] ]) tooltip "ITMTunneling"
            else:
                frame xsize 80 ysize 80 pos 780+cCols[i]+32, 350+cRows[j]+34 background Solid("#ffffff00"):
                    image "03_minigames/ico_slot_subunit.png" xalign 0.5 yalign 0.5
                    button action Return([ "subunit", False, [j,i] ])
                 
            


    #####################################################################
    #                SYSTEM TALLY
    #####################################################################
    vbox xsize 300 spacing 20 pos 1420, 370:
        text C_HI_B+"Subsystem Status"+C_HI_E
        text "{}".format(GAME.ship.getSubSysRating(subSysKey))
        text C_HI_B+"Efficiency"+C_HI_E
        text "{:.1f} %".format(GAME.ship.getSubSysStatus(subSysKey))
        text C_HI_B+"Output Power"+C_HI_E
        text "{:.2f} GW".format(GAME.ship.getSubSysOutput(subSysKey))



    $ tooltip = GetTooltip()
    if tooltip:
        if tooltip in GAME.items.keys():
            $ item = GAME.items[tooltip]
            vbox pos 800, 750 xsize 500:
                text "{} - {}".format(item.getName(["noArt", "cap", "col"]), item.description)  size FSIZE

    #####################################################################
    #                EXIT BUTTON, KEYS, ...
    #####################################################################
    frame xsize 350 ysize 64 pos 0,900 background Solid("#00000000") padding 0,0:
        image "05_gui/gui_menu_option.png" yalign 0.5
        button action Return ("exit") xpos 20
        textbutton "Exit (X)" yalign 0.5 action Return("exit") xpos 20 # CR-0587
        key "x" action Return ("exit")
        key "X" action Return ("exit")
    vbox  xalign 0.5 yalign 0.95:
        text "CURSOR R/L = Next/Previous Subsystem" size FSIZE_MED


label mg_maintenance():
    # ===== CR-0784 START
    if GAME.ship.cargoLoaded() > GAME.ship.cargoLimit():
        if not bb_2.hasDone("cargo_warning"):
            queue sound "audio/drone_beep.wav"
            bb2 "\"The ship is overloaded, Captain [GAME.mc.name]!\""
            bb2 "\"System maintenance is too dangerous in that condition...\""
            bb2 "\"I recommend you adapt your cargo first from the Cargo Manager.\""
            mc "\"Ah, right...\""
        else:
            queue sound "audio/tech_fail.wav"
            "[C_RE_B]System Warning[C_RE_E]" "\"Cargo Overload - System Access Blocked.\""
            mc "\"I better adjust my cargo first...\""
        return()
    # ===== CR-0784 END

    # Initialize
    $ GAME.mc.hasDone("engine")
    scene room_engine_smart
    show image "03_minigames/bg_maintenance.png"
    show screen header
    $ subSystems = ["engines", "shields", "weapons", "launcher", "mining", "cargo", "hyperdrive", "uplink"]
    # Maintenance Loop
    while True:
        call screen mg_maintenance_scr(subSystems[0])
        if _return == "exit":
            $ exit_confirmed = True
            queue sound "audio/click.wav"
            if GAME.ship.cargoLoaded() > GAME.ship.cargoLimit():
                call large_notify("WARNING!", "Your reconfiguration has reduced cargo bay capacity. Cargo items will randomly be eliminated to adjust to safe compression limits.\n\nReconfiguration of your Cargo Compressor System is recommended.", ["Ignore", "Reconfigure"], "08_items/ico ITMCargoMkI.png", "red") from _call_large_notify_16
                if _return == "Ignore":
                    $ amount = 0
                    while GAME.ship.cargoLoaded() > GAME.ship.cargoLimit():
                        $ item = random.choice(GAME.ship.cargo)
                        $ GAME.ship.cargo.remove(item)
                        $ amount += 1
                    play sound "audio/load.wav"
                    call simple_notify("CARGO ADJUSTMENT", "{} t of cargo eliminated".format(amount), ["Continue"]) from _call_simple_notify_15
                else:
                    $ exit_confirmed = False
            if exit_confirmed:
                hide image "03_minigames/bg_maintenance.png"
                if GAME.ship.getSubSysStatus("engines") > 99 and "explorer" not in GAME.mc.achievements:
                    queue sound "audio/success.wav"
                    call large_notify("ACHIEVEMENT GAINED - EXPLORER", "Congratulations, you have brought your engines up to 100 percent performance!\n\nYou can now access the farthest reaches of this system.", ["Continue"], "08_items/ico ITMCup.png", "pink") from _call_large_notify_17
                    $ GAME.mc.achievements.append("explorer")    
                #call quest_updater()  # CR-0321          
                return()


        elif "left" in _return:
            play sound "audio/click.wav"
            $ subSystems = subSystems[-1:]+ subSystems[:-1]
        elif "right" in _return:
            play sound "audio/click.wav"
            $ subSystems = subSystems[1:]+ subSystems[:1]

        elif "systype" in _return:
            $spos = _return[1]
            play sound "audio/click.wav"
            $ s_ind = subSystems.index(spos)
            $ subSystems.pop(s_ind)
            $ subSystems.insert(0, spos)


        elif "subunit" in _return and GAME.ship.hasSubSys(subSystems[0]):
            play sound "audio/click.wav"
            # if occupied uninstall
            $ matrixPos = _return[2]
            if _return[1]:
                play sound "audio/install.wav"
                $ GAME.ship.uninstallSubunit(subSystems[0], matrixPos)
            # if empty select install
            else:
                hide image "03_minigames/bg_maintenance.png"
                hide screen header
                call item_show(GAME.ship.cargo, ["subunit"], "CARGO - SUBUNITS", ["ITMAICoreElite"]) from _call_item_show
                if _return:
                    $ item = _return
                    # install
                    $ output = GAME.ship.getSubSysStatus(subSystems[0])
                    $ result = GAME.ship.installSubunit(subSystems[0], item.ID, matrixPos)
                    if result:
                        if GAME.ship.getSubSysStatus(subSystems[0]) > output:
                            play sound "audio/tech_success.wav"
                        else:
                            play sound "audio/install.wav"

                    else:
                        play sound "audio/tech_fail.wav"
                        mc "\"I think this subunit belongs elsewhere...\""
                show image "03_minigames/bg_maintenance.png"
                show screen header
        # ======== DEPRECATED
        elif "loadout" in _return: # 
            $ slot = _return[1]
            if GAME.ship.loadout[slot]:  # uninstall
                queue sound "audio/install.wav"
                $ GAME.ship.loadWare(GAME.ship.loadout[slot].ID)
                $ GAME.ship.loadout[slot] = False
            else: # install
                show image "room_engine_smart"
                call item_show(GAME.ship.cargo, ["torpedo"], "CARGO - TORPEDOES") from _call_item_show_1
                hide image "room_engine_smart"            
                $ torp = _return
                if torp:
                    queue sound "audio/install.wav"
                    $ GAME.ship.loadout[slot] = torp 
                    $ GAME.ship.unloadWare(torp.ID)
        # ========
        elif "addon" in _return:
            $ subSysKey = _return[1]
            $ slot = _return[2]
            $ equipped = _return[3]
            # addon selection
            if equipped:
                $ result = GAME.ship.unEquipAddOn(subSysKey, slot)
                if result:
                    play sound "audio/install.wav"
                else:
                    play sound "audio/tech_fail.wav"
            else:
                show image "room_engine_smart"
                call item_show(GAME.ship.cargo, ["module"], "CARGO - ADDON MODULES") from _call_item_show_2
                hide image "room_engine_smart"                 
                $ item = _return 
                if _return:
                    if item in GAME.ship.supportedAddOns(subSysKey):
                        $ GAME.ship.equipAddOn(subSysKey, item.ID, slot)
                        $ GAME.ship.cargo.remove(item)
                        play sound "audio/install.wav"
                    else:
                        play sound "audio/tech_fail.wav"
        else:
            play sound "audio/tech_fail.wav"
            #"[_return]"

    return()
