#####################################################################
#					UNIFORM AND ORDER SYSTEM		
#####################################################################


#####################################################################
#					INITIALIZE		
#####################################################################
label init_orders():
    #####################################################################
    #                CHARACTER OUTFITS
    #####################################################################
    $ uniformData = [ 

        ["UID1_Free", "Free Uniform", "A uniform chosen by the crew member", 
            {}, {}, True, "ITMUniformFree"], 
        ["UID2_Racy", "Racy Uniform", "A racy, but still somewhat practical uniform", 
            {"EXH": 1, "MOD": 20}, {"MOD": -10}, False, "ITMUniformRacy"], 
        ["UID3_Revealing", "Revealing Uniform", "A quite revealing and impractical uniform", 
            {"EXH":4, "MOD": 40}, {"MOD":-20}, False, "ITMUniformRevealing"], 

        ["UID4_Krell", "Krell Uniform", "A 'uniform' required in Krell Space for crew members", 
            {"EXH":7, "SUB": 3, "MOD": 20}, {"MOD": -40}, False, "ITMUniformKrell"], 

        ["UID5_Nude", "Naked Duty", "Clothing protocol for naked duty", 
            {"EXH":10, "MOD": 20}, {"MOD": -50}, False, "ITMUniformNude"]
    ]

    python:
        for i in uniformData:
            GAME.uniformDB[i[0]] = UniformOrder(i[0], i[1], i[2], i[3], i[4], i[5], i[6])

    #####################################################################
    #					JOBS		
    #####################################################################
    $ jobData = [ 
        ["JOB_Idle", "Relaxing", "Relaxing (Reduces Stress)", {}, {"STS": -50, "MOD": +5}],

        #T'Ris
        ["JOB_Diag", "Run Diagnostics", "Analyzing the ship's condition", {}, {"STS": 5}],
        ["JOB_Pods", "Resupply Pods", "Resupply ship with pods (max 5) on docking", {}, {"STS": 5}],
        ["JOB_Nav", "Nav Class", "Attend hyperspace navigation class", {}, {"STS": 20}],
        ["JOB_Pet", "Pet Class", "Attend pet training class for the day", {}, {"STS": 50}],

        # Nimhe
        ["JOB_Parts", "Get Bot Crates", "Acquire Bot crates on the market.", {}, {"STS": 10}],
        ["JOB_Shell_J", "Craft New Shell", "Craft Bot shells - Type J (uses 1 Bot crate)", {}, {"STS": 30}],
        ["JOB_Assy", "Assemble Bots", "Assembling and training of Bots", {}, {"STS": 15}],
        ["JOB_Hunt", "Hunt For Parts", "Hunt for specific Bot parts", {}, {"STS": 10}],
        ["JOB_Upgrade", "Upgrade Parts", "Create higher grade parts (3x) from 3 lower", {}, {"STS": 10}],

        # Khelara
        ["JOB_Loadout", "Torpedo Loadout", "Ensure Torpedoes are equipped before battle and reload in battle (1 per 9 AP).", {}, {"STS": 10}],
        ["JOB_Repair", "Ship Repairs", "Automatically address ship repairs", {}, {"STS": 5}],

        # Vee
        ["JOB_Astro", "Space Survey", "Analyse current system for Anomalies worth to explore", {}, {"ENE": 10}],

       # Seraphine
        ["JOB_Shop", "Shopping", "Browse SectorNet for surprise deals...", {}, {"STS": 10}],



    ]
    
    python:
        for i in jobData:
            GAME.jobDB[i[0]] = Job(i[0], i[1], i[2], i[3], i[4])
    return()

#####################################################################
#					CREW ASSESSMENT		
#####################################################################
label crew_assessment():
    $ GAME.reports = []

    python:
        uniform_crew = set(GAME.crew) - set([bb_2, vee])
        if GAME.questSys.isActive("QID_VEE_FAMILIARIZE"):
            uniform_crew.add(vee)
        # crew stress bonus 
        if "INV_ENTERTAINMENT" in GAME.investments:
            for actor in uniform_crew:
                actor.attr["STS"] = capValue(actor.attr["STS"]-5, 0,100)

        # crew mood assessment
        for actor in uniform_crew:
            
            if actor.uniform == "UID2_Racy":
                actor.tallyUp("Racy Uniform", 1)
                actor.incAttrFrac("EXH", 0.5, 3)

            elif actor.uniform == "UID3_Revealing":
                actor.tallyUp("Revealing Uniform", 1)
                actor.incAttrFrac("EXH", 0.5, 6)

            # transfer infractions
            if [x for x in actor.status if "INF_" in x]:
                actor.hasDoneToday(x)
                actor.status.remove(x)

            # check, whether mood is high enough for uniform, revert if not
            if not actor.uniformOK(actor.uniform): # current order NOK:
                GAME.reports.append(["UNIFORM REFUSAL!", "{} is in a bad mood and no longer wants to wear her assigned uniform.\n\nImprove her mood with presents or let her relax for a day or two.".format(C_HI_B+actor.name+C_HI_E), ["Continue"], "08_items/ico ITMUniformRacy.png", "blue"])
                actor.uniform = "UID1_Free"
                actor.getDressed("override")
            
            # check, whether stress is too high for work 
            if actor.attr["STS"] > 80:
                GAME.reports.append(["TASK REFUSAL!", "{} is too stressed out to perform her duties today. \n\nI suggest you let her relax for a day or two.".format(C_HI_B+actor.name+C_HI_E), ["Continue"], "08_items/ico ITMSpanner.png", "blue"])
                actor.setJob("JOB_Idle")

            # # check EXH increase by uniform
            # if actor.getTally("Racy Uniform") >= 3 and actor.attr["EXH"] == 2:
            #     actor.attr["EXH"] = 3 
            #     GAME.reports.append(["ATTRIBUTE INCREASE!", "Having worn her Racy Uniform for 3 days, the exhibitionism skill of {} has increased. \n\nContinue training her in that manner!".format(C_HI_B+actor.name+C_HI_E), ["Continue"], "08_items/ico ITMUniformRacy.png", "blue"])

            # elif actor.getTally("Racy Uniform") >= 6 and actor.attr["EXH"] == 3:
            #     actor.attr["EXH"] = 4 
            #     GAME.reports.append(["ATTRIBUTE INCREASE!", "Having worn her Racy Uniform for 3 days, the exhibitionism skill of {} has increased. \n\nConsider choosing a more challenging outfit for her!".format(C_HI_B+actor.name+C_HI_E), ["Continue"], "08_items/ico ITMUniformRacy.png", "blue"])

            # elif actor.getTally("Revealing Uniform") >= 3 and actor.attr["EXH"] == 5:
            #     actor.attr["EXH"] = 6 
            #     GAME.reports.append(["ATTRIBUTE INCREASE!", "Having worn her Revealing Uniform for 3 days, the exhibitionism skill of {} has increased. \n\nContinue training her in that manner!".format(C_HI_B+actor.name+C_HI_E), ["Continue"], "08_items/ico ITMUniformRevealing.png", "blue"])

            # elif actor.getTally("Revealing Uniform") >= 6 and actor.attr["EXH"] == 6:
            #     actor.attr["EXH"] = 7 
            #     GAME.reports.append(["ATTRIBUTE INCREASE!", "Having worn her Revealing Uniform for 3 days, the exhibitionism skill of {} has increased. \n\nConsider choosing a more challenging outfit for her! (Future Version)".format(C_HI_B+actor.name+C_HI_E), ["Continue"], "08_items/ico ITMUniformRevealing.png", "blue"])

    while GAME.reports:
        $ report = GAME.reports.pop(0)
        queue sound "audio/notify.wav"
        call large_notify(report[0], report[1], report[2], report[3], report[4]) from _call_large_notify_50
    return()

#####################################################################
#					DAILY ORDERS		
#####################################################################
screen daily_orders_scr(*args):
    $ crew = args[0] # CR-0326
    $ yadj = args[1]
    text C_HI_B+"DAILY ORDERS"+C_HI_E size FSIZE_LARGE pos 960, 80 xalign 0.5



    side "c r":
        area 100,180,1800,620
        viewport id "vp":
            draggable True
            mousewheel True 
            yadjustment yadj

            # ----- viewport content
            # Crew members list
            vbox spacing 60 xalign 0.5 ypos 200:
                for actor in crew:
                    frame xsize 1700 ysize 96 xalign 0.5 background Solid ("#0099cc88"):
                        image "01_portrait/ico_char_{}.png".format(actor.ID.lower()) xpos 20 zoom 0.5 
                        if actor.getLocOverride():
                            image "05_gui/away_hover.png" pos 30,-5
                        $ sts = percentColorized(actor.attr["STS"],[0,100], True)
                        if actor == vee:
                            $ ene = percentColorized(actor.attr["ENE"], [0,100])
                            text "Stress: {}{:4d}%{}".format(sts[1],sts[3], sts[2], mod[1]) yalign 0.5 xpos 200  
                            text "Energy: {}{:5d}%{}".format(ene[1], ene[3], ene[2]) yalign 0.5 xpos 400               
                        else:
                            $ mod = percentColorized(actor.attr["MOD"], [0,100])   
                            text "Stress: {}{:4d}%{}".format(sts[1],sts[3], sts[2], mod[1]) yalign 0.5 xpos 200  
                            text "Mood: {}{:5d}%{}".format(mod[1], mod[3], mod[2]) yalign 0.5 xpos 400 
                        
                        # actor specific mood improvement 
                        $ gift = {"ACTNIMHE": "ITMLiquorFairy", "ACTTRIS": "ITMCandle", "ACTKHELARA": "ITMLiquorDrengar", "ACTVEE": "ITMPodEnergy", "ACTSERA": "ITMLiquorVortex", "ACTMOIRA": "ITMLiquorIltari"}[actor.ID]
                        $ item = GAME.items[gift]
                        frame xsize 96 ysize 96 background Solid ("#ffffff00") xpos 610 yalign 0.5:
                            image "08_items/ico {}.png".format(item.ID) xalign 0.5 yalign 0.5 zoom 0.25 
                            if gift == "ITMPodEnergy":
                                if GAME.ship.hasCargo([item.ID]):
                                    button action Return(["present", actor, item]) 
                                text "{}x".format(GAME.ship.cargo.count(item))  yalign 0.5 xpos 140 xalign 1.0
                            else:
                                if GAME.mc.hasItem(item.ID):
                                    button action Return(["present", actor, item]) 
                                text "{}x".format(GAME.mc.inventory.count(item))  yalign 0.5 xpos 140 xalign 1.0
                    


                        frame xsize 200 ysize 48  yalign 0.5 xpos 800 background Solid("#0099ccff"):
                            text "{}".format(actor.getJob().name) yalign 0.6 xalign 0.5 size FSIZE
                            button action Return(["job", actor])
                        frame xsize 200 ysize 48  yalign 0.5 xpos 1100 background Solid("#0099ccff"):
                            text "{}".format(GAME.uniformDB[actor.uniform].name) yalign 0.6 xalign 0.5 size FSIZE
                            button action Return(["uniform", actor])
                        if [x for x in GAME.infractions if x[0] == actor]:
                            frame xsize 200 ysize 48  yalign 0.5 xpos 1400 background Solid("#0099ccff"):
                                text "Discipline".format() yalign 0.6 xalign 0.5 size FSIZE
                                button action Return(["discipline", actor])
                text " "
            # ----- viewport content end
        vbar value YScrollValue("vp")




    # Exit button 
    frame xsize 350 ysize 64 pos 0,900 background Solid("#00000000") padding 0,0:
        image "05_gui/gui_menu_option.png" yalign 0.5
        textbutton "Start Day (D)" yalign 0.5 action Return(False) xpos 20
        key "d" action Return(False)
        key "K_SPACE" action Return(False)
        button action Return(False) xpos 20    

label daily_orders():
    show image "05_gui/mask 50.png"
    $ yadj = ui.adjustment()

    $ crew = [tris]
    if nimhe in GAME.crew:
        $ crew.append(nimhe)
    if khelara in GAME.crew:
        $ crew.append(khelara)     
    if moira in GAME.crew:
        $ crew.append(moira)
    if GAME.questSys.isActive("QID_VEE_FAMILIARIZE"):
        $ crew.append(vee)
    if seraphine in GAME.crew:
        $ crew.append(seraphine)


    $ uniformLoop = True

    while uniformLoop:
        call screen daily_orders_scr(crew, yadj)
        if _return == False:
            $ canExit = True
            queue sound "audio/click.wav"
            hide image "05_gui/mask 50.png" 
            # exit checks
            if khelara.uniform == "UID2_Racy":
                call transaction("Uniform Duty Surcharges", -2500, True) from _call_transaction_28            
            elif khelara.uniform == "UID3_Revealing":
                call transaction("Uniform Duty Surcharges", -5000, True) from _call_transaction_29            
            elif khelara.uniform == "UID4_Krell":
                call transaction("Uniform Duty Surcharges", -10000, True) from _call_transaction_30            

            # off board assignments 
            if tris.getJob().ID == "JOB_Nav" and (GAME.ship.status != "docked" or GAME.getSpaceLoc().ID != "LIDStationIltari") and not tris.getLocOverride():
                queue sound "audio/notify.wav"
                "You must be docked in Iltari station to send T'Ris to Nav Class."
                $ canExit = False
            elif tris.getJob().ID == "JOB_Pet" and not (GAME.ship.status == "docked" and GAME.getSpaceLoc().ID == "LIDStationArellarti") and not tris.getLocOverride():
                queue sound "audio/notify.wav"
                "You must be docked in Arellarti Station to send T'Ris to Pet Class."
                $ canExit = False
            elif tris.getJob().ID == "JOB_Pet" and  not any([tris.hasItem(x) for x in ["ITMVoucherPet1", "ITMVoucherPet2", "ITMVoucherPet3"]]):
                queue sound "audio/notify.wav"
                "T'Ris must have a valid training voucher to attend Pet Class."
                $ canExit = False

            elif tris.getJob().ID == "JOB_Nav" and not tris.getLocOverride():
                $ tris.setLocOverride("LOCNavClass")
                queue sound "audio/notify.wav"
                call large_notify("OFF BOARD ASSIGNMENT", "T'Ris leaves for her away mission. She will rejoin you from 18:00 if you are docked at Iltari Station.", ["Continue"], "05_gui/ico Ship.png") from _call_large_notify_51
                $ tris.hasDoneToday("away_mission")
            elif tris.getJob().ID == "JOB_Pet" and not tris.getLocOverride():
                $ tris.setLocOverride("LOCPetClass")
                queue sound "audio/notify.wav"
                call large_notify("OFF BOARD ASSIGNMENT", "T'Ris leaves for a day of Pet Class.\n\nShe will rejoin you from 18:00 if you are docked at Arellarti Station.", ["Continue"], "05_gui/ico Ship.png") from _call_large_notify_52
                $ tris.hasDoneToday("away_mission")

            #OhWee mod: Nimhe bot crafting options
            elif nimhe.getJob().ID == "JOB_Shell_J":
                if GAME.money < 75000:
                    queue sound "audio/notify.wav"
                    "You currently do not have enough credits to choose this option..."
                    $ canExit = False
                else:
                    $ Shell_Crafting_Selection = ""
                    queue sound "audio/notify.wav"
                    call large_notify("SELECT SHELL TYPE", "Nimhe can craft the following shell types", new_shell_types, "01_portrait/ico_char_actnimhe.png") from _call_large_notify_2n
                    $ Shell_Crafting_Selection = _return
            ### End OhWee mod code

            if canExit:
                $ uniformLoop = False

        elif _return[1].getLocOverride():
            $ actor = _return[1]
            queue sound "audio/notify.wav"
            "[actor.name] is not available for orders at the moment."

        elif "job" in _return:
            queue sound "audio/click.wav"
            $ actor = _return[1] 
            if actor.attr["STS"] > 80:
                play sound "audio/notify.wav"
                call large_notify("STRESSED OUT", "{} is too stressed out to perform a task today. Let her relax for a day or two.\n\nYou might also reduce her stress level by a suitable present.".format(C_HI_B+actor.name+C_HI_E), ["Continue"], "08_items/ico ITMSpanner.png", "red") from _call_large_notify_53
            else:
                $ actor = _return[1] 
                $ actor.nextJob()
          
        elif "uniform" in _return:
            queue sound "audio/click.wav"
            $ actor = _return[1] 
            if actor == vee: # CR-0852
                mc "\"I think V's uniform is just fine...\""
            else:
                call uniform_orders(actor) from _call_uniform_orders

                if _return:
                    $ uniformOrder = _return
                    $ uniform = GAME.uniformDB[uniformOrder]
                    $ actor.uniform = uniform.ID
                    if actor.uniform != "ITMUniformFree":
                        $ GAME.mc.hasDone("uniform_muster") # first uniform assign quest done
                    $ actor.getDressed()

        
        elif "present" in _return:
            $ actor = _return[1]
            $ item = _return[2]
            if actor.hasDoneToday("gift") and actor != vee:
                mc "\"I shouldn't overdo it with the gifts.\""
            elif actor != vee:
                queue sound "audio/click_soft.wav"
                $ GAME.mc.passItem(item.ID, actor)
                call attr_mod(actor, "MOD", 50, 100, 100, False) from _call_attr_mod_80
                $ vee.tallyUp("Energy Consumed",1)
            elif actor == vee:
                queue sound "audio/click_soft.wav"
                $ vee.inventory.append(item)
                $ GAME.ship.unloadWare(item.ID)
                call attr_mod(actor, "ENE", 50, 100, 100, False) from _call_attr_mod_81

            queue sound "audio/click.wav"


        elif "discipline" in _return:
            $ actor = _return[1]
            $ issue = GAME.infractions[0]
            queue sound "audio/notify.wav"
            mc "\"We have a Discipline Issue this morning!\""
            mc "\"[actor.name], you committed an infraction.\""
            mc "\"Specifically, you [issue[1]].\""
            $ renpy.say(GAME.adv[actor.ID], vary("Hrmmpfff..."))
            mc "\"Proceed to the Mess Room for Administrative Disciplining.\""
            scene intermission with fade
            "A short while later in the Mess Room..."
            hide screen header
            call mg_spanking("DISCIPLINING - {}".format(actor.name.upper()), actor) from _call_mg_spanking
            show screen header()
            scene room_captain_smart with fade
            $ GAME.infractions = []
            
        else:
            queue sound "audio/click.wav"


    #####################################################################
    #					PROCESS DAILY ORDER EFFECTS		
    #####################################################################
    # uniform progression counters 
    python:
        for actor in [tris]:
            if actor.uniform == "UID1_Free":
                # determine progressive variation 
                uniform = actor.getProgOutfit()

                # moved to night passes housekeeping
                # # increase counter 
                # actor.counters[uniform.ID] = actor.counters.get(uniform.ID, 0) + 1

    return()

#####################################################################
#					UNIFORM ORDERS		
#####################################################################

screen uniform_orders_scr(uniforms, actor=False):
    # headline and headers
    text C_HI_B+"{} - DRESS CODE".format(actor.name.upper())+C_HI_E size FSIZE_LARGE xalign 0.5 ypos 100
    frame xalign 0.5 yalign 0.45 xsize 1920 ysize 180 background Solid ("#0099ccff")
    hbox xalign 0.5 yalign 0.45 spacing 20:
        for uniform in uniforms:
            if actor.hasItem(uniform.itemID) or uniform.itemID == "ITMUniformFree":
                frame xsize 200 ysize 400:
                    if uniform.itemID == "ITMUniformFree": # Free
                        image "05_gui/gui_mannikin_{}.png".format(uniform.ID) xalign 0.5 yalign 0.5 zoom 0.65
                        button action Return(uniform) tooltip uniform
                    elif actor.hasItem(uniform.itemID): # Owns
                        image "05_gui/gui_mannikin_{}.png".format(uniform.ID) xalign 0.5 yalign 0.5 zoom 0.65
                        button action Return(uniform) tooltip uniform
                    else:
                        image "05_gui/ico_gui_padlock.png" xalign 0.5 yalign 0.5 zoom 0.25 
                        # button action NullAction() tooltip uniform
                    #hbox ypos 420 xsize 180:
                        #text "{}".format(uniform.name) size FSIZE xalign 0.5
                

    $ tooltip = GetTooltip()
    if tooltip:   
        vbox xalign 0.5 yalign 0.8:
            $ req = "None"
            if tooltip.req:
                $ req = ""
                for k in tooltip.req.keys():
                    $ C_B , C_E = C_GR_B, C_GR_E
                    if not actor.meetsReq(k, tooltip.req):
                        $ C_B , C_E = C_RE_B, C_RE_E
                    $ req += C_B+"{} {}  ".format(k, tooltip.req[k])+C_E

            text C_HI_B+"{}".format(tooltip.name).upper()+C_HI_E
            text tooltip.description

            text "Requirements: " + req  

    #####################################################################
    #                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(False)
        textbutton "Exit (X)" yalign 0.5 action Return(False) xpos 20 # CR-0587
        key "x" action Return(False)
        key "X" action Return(False)
  
label uniform_orders(actor):
    $ uniforms = GAME.uniformDB.values()
    $ uniforms.sort(key = lambda x : x.ID)

    while True:
        call screen uniform_orders_scr(uniforms, actor)
        queue sound "audio/click.wav"
        $ refusal = []
        # intercepts 

        if _return == False:
            return()

        elif _return.ID == "UID4_Krell" and GAME.getStarSys().race == "Krell":
            return(_return.ID)

        elif _return.ID != "UID4_Krell" and GAME.getStarSys().race == "Krell":
            queue sound "audio/notify.wav"
            mc "{i}\"I better keep my crew in Krell mandated attire...\"{/i}"
            mc "{i}\"Would hate to get my endorsement for Krell Space withdrawn...\"{/i}"
            return()

        elif actor.uniformOK(_return.ID):
            return(_return.ID)

        elif not actor.uniformOK(_return.ID, ["EXH"]):
            $ actor.getDressed()
            queue sound "audio/notify.wav"
            $ refusal.append("I prefer to chose my own uniform today.")
            $ refusal.append("This one is inappropriate.")

        elif not actor.uniformOK(_return.ID, ["SUB"]):
            $ actor.getDressed()
            queue sound "audio/notify.wav"
            $ refusal.append("I won't wear that uniform.")
            $ refusal.append("It is demeaning.")

        elif not actor.uniformOK(_return.ID, ["MOD"]):
            $ actor.getDressed()
            queue sound "audio/notify.wav"
            $ refusal.append("I prefer to chose my own uniform today.")
        else:
            $ actor.getDressed()
            queue sound "audio/notify.wav"
            $ refusal.append("I won't wear that uniform.")

        # ===== CR-0745 START
        # Exceptions
        if _return.ID == "UID4_Krell" and actor == moira and refusal and GAME.getStarSys().race == "Krell":
            $ refusal = ["Nice try.", "I told you that I have Krell Exception Form 49/B."]
        # ===== CR-0745 END

        # Response
        if _return.ID == "UID4_Krell" and GAME.getStarSys().race != "Krell":
            $ refusal = ["We are not in Krell Space."]+refusal

        while refusal:
            $ msg = refusal.pop(0)
            GAME.adv[actor.ID] "\"[msg]\""

            
    return()


