package com.dunerealms.gui; import com.google.gson.*; import java.util.*; import java.util.function.*; import org.bukkit.*; import org.bukkit.entity.Player; import org.bukkit.event.*; import org.bukkit.event.inventory.*; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.*; import org.bukkit.plugin.java.JavaPlugin; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.event.ClickEvent; /** Presentation and input only: every mutation is revalidated by the central quest engine. */ final class QuestMenus implements Listener { private final JavaPlugin plugin;private final HouseBridge bridge;private final Consumer back; private final Map pending=new HashMap<>(); private static final class Panel implements InventoryHolder { final UUID owner;final GuiSession gate;final Map actions=new HashMap<>();final List choices=new ArrayList<>();final Inventory inventory;final String title;String description="Your current J.A.R.V.I.S. mission journal"; Panel(Player p,String title){owner=p.getUniqueId();gate=new GuiSession(owner);this.title=title;inventory=Bukkit.createInventory(this,54,Component.text(title,NamedTextColor.GOLD));} public Inventory getInventory(){return inventory;} } QuestMenus(JavaPlugin plugin,HouseBridge bridge,Consumer back){this.plugin=plugin;this.bridge=bridge;this.back=back;Bukkit.getPluginManager().registerEvents(this,plugin);} void quartermaster(Player p,Runnable exchange,Runnable kits){var s=panel(p,"Gurney · Quartermaster");put(s,20,"Exchange","Buy and sell individual items",Material.EMERALD,exchange);put(s,22,"Missions & turn-ins","Collect your House T0 kit or repair its original armour.\nPrepare four parts: one iron ingot, leather, copper ingot and quartz.\nOther missions and rewards use your current central journal.",Material.WRITABLE_BOOK,()->open(p));put(s,24,"Stillsuit kits","Published clan, company and office kits",Material.NETHERITE_CHESTPLATE,kits);put(s,49,"Close","Return to the world",Material.ARROW,p::closeInventory);show(p,s);} private static String text(JsonObject row,String key,String fallback){return row.has(key)&&!row.get(key).isJsonNull()?row.get(key).getAsString():fallback;} private static boolean yes(JsonObject row,String key){return row.has(key)&&!row.get(key).isJsonNull()&&row.get(key).getAsBoolean();} private static boolean website(JsonObject row){return row.has("executionRequirements")&&!row.get("executionRequirements").isJsonNull()&&yes(row.getAsJsonObject("executionRequirements"),"website")&&!yes(row.getAsJsonObject("executionRequirements"),"minecraft");} private Panel panel(Player p,String title){var screen=new Panel(p,title);var filler=new ItemStack(Material.GRAY_STAINED_GLASS_PANE);var meta=filler.getItemMeta();meta.displayName(Component.empty());filler.setItemMeta(meta);for(int i=0;i<54;i++)screen.inventory.setItem(i,filler);return screen;} private void put(Panel panel,int slot,String title,String description,Material material,Runnable action){ var item=new ItemStack(material);var meta=item.getItemMeta();meta.displayName(Component.text(title,NamedTextColor.GOLD));meta.lore(Arrays.stream(description.split("\n")).map(line->Component.text(line,NamedTextColor.GRAY)).toList());item.setItemMeta(meta);panel.inventory.setItem(slot,item); if(action==null)panel.description+="\n\n"+title+"\n"+description; if(action!=null){panel.actions.put(slot,action);panel.choices.add(new BedrockForms.Choice(title,description,action));} } private void show(Player p,Panel screen){if(BedrockForms.isBedrock(p)){BedrockForms.show(plugin,p,screen.title,screen.description,List.copyOf(screen.choices));return;}p.openInventory(screen.inventory);Bukkit.getScheduler().runTaskLater(plugin,screen.gate::expire,2400L);} void close(){pending.clear();for(Player p:Bukkit.getOnlinePlayers())if(p.getOpenInventory().getTopInventory().getHolder() instanceof Panel)p.closeInventory();} void open(Player p){var screen=panel(p,"Mission journal");put(screen,20,"Personal Experience","Your personal mission branches",Material.BOOK,()->load(p,"personal",null,null,0));put(screen,24,"Reputation","Your Reputation mission branches",Material.ENCHANTED_BOOK,()->load(p,"pol",null,null,0));put(screen,45,"Website Mentat Report","Open your full online journal",Material.MAP,()->website(p));put(screen,49,"Back","Imperial Codex",Material.ARROW,()->back.accept(p));show(p,screen);} private void website(Player p){p.closeInventory();p.sendMessage(Component.text("Open your Mentat Report →",NamedTextColor.GOLD).clickEvent(ClickEvent.openUrl("https://clans.dunerealms.com/#quests/quests")));} private void request(Player p,JsonObject input,Consumer result){ UUID owner=p.getUniqueId();if(pending.containsKey(owner))return;UUID operation=UUID.randomUUID(),world=p.getWorld().getUID();pending.put(owner,operation);p.closeInventory();p.sendMessage(Component.text("Jarvis executing matrix",NamedTextColor.GOLD)); Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{JsonObject data=null;String error=null;try{data=bridge.quests(owner,input);}catch(Exception failure){error=failure instanceof java.io.IOException?failure.getMessage():"The mission journal is unavailable. Reopen it before retrying.";}JsonObject received=data;String message=error;if(!plugin.isEnabled())return; Bukkit.getScheduler().runTask(plugin,()->{if(!operation.equals(pending.get(owner)))return;pending.remove(owner);if(!p.isOnline()||!world.equals(p.getWorld().getUID()))return;if(message!=null){p.sendMessage(message);return;}if(p.getOpenInventory().getType()!=InventoryType.CRAFTING)return;result.accept(received);}); }); } private void load(Player p,String kind,String branch,String selected,int page){var input=new JsonObject();input.addProperty("action","read");input.addProperty("kind",kind);request(p,input,data->{if(!"active".equals(text(data,"state",""))){p.sendMessage("No active quest season is available.");open(p);return;}if(branch==null)branches(p,kind,data);else if(selected==null)quests(p,kind,data,branch,page);else{JsonObject row=null;for(var entry:data.getAsJsonArray("quests"))if(selected.equals(text(entry.getAsJsonObject(),"id","")))row=entry.getAsJsonObject();if(row==null)quests(p,kind,data,branch,page);else details(p,kind,data,branch,page,row);}});} private void branches(Player p,String kind,JsonObject data){ var screen=panel(p,kind.equals("pol")?"Reputation branches":"Personal mission branches");var branches=new LinkedHashMap();for(var entry:data.getAsJsonArray("quests")){String id=text(entry.getAsJsonObject(),"branch","missions");branches.putIfAbsent(id,id);} if(data.has("branches"))for(var entry:data.getAsJsonArray("branches")){var branch=entry.getAsJsonObject();String id=text(branch,"id","");if(branches.containsKey(id))branches.put(id,text(branch,"title",id));} int slot=0;for(var branch:branches.entrySet()){if(slot>=45)break;String id=branch.getKey();put(screen,slot++,branch.getValue(),"Open this mission branch",Material.WRITABLE_BOOK,()->quests(p,kind,data,id,0));}put(screen,49,"Back","Mission journal",Material.ARROW,()->open(p));show(p,screen); } private void quests(Player p,String kind,JsonObject data,String branch,int page){ var rows=new ArrayList();for(var entry:data.getAsJsonArray("quests")){var row=entry.getAsJsonObject();if(branch.equals(text(row,"branch","")))rows.add(row);} int offset=page*36;var screen=panel(p,"Missions · "+branch);for(int i=offset;idetails(p,kind,data,branch,page,row));} put(screen,45,"Branches","Choose another branch",Material.ARROW,()->branches(p,kind,data));if(page>0)put(screen,47,"Previous","Previous missions",Material.PAPER,()->quests(p,kind,data,branch,page-1));put(screen,49,"Refresh","Read current verified quest records",Material.CLOCK,()->load(p,kind,branch,null,page));if(offset+36quests(p,kind,data,branch,page+1));show(p,screen); } private void details(Player p,String kind,JsonObject data,String branch,int page,JsonObject row){ var screen=panel(p,"Quest dossier");String title=text(row,"title","Quest"),state=text(row,"state","Pending"),description=text(row,"objective","Complete the verified objective.")+"\nProgress: "+text(row,"progress","0")+" / "+text(row,"target","0")+"\nState: "+state+"\n"+(kind.equals("pol")?"Reputation: ":"XP: ")+text(row,"xp","Not configured"); put(screen,13,title,description,website(row)?Material.WRITABLE_BOOK:Material.LIGHT_BLUE_DYE,null); if(website(row))put(screen,31,"Open website journal","This objective belongs to the website",Material.MAP,()->website(p)); else if(yes(row,"canClaim"))put(screen,31,"Claim verified reward","Revalidate the objective and current reward",Material.LIME_DYE,()->act(p,kind,branch,page,row,"claim")); else if(text(row,"metric","").equals("citizen-introduction")&&state.equals("active"))put(screen,31,"Read citizen briefing","Read and acknowledge your Imperial Citizen introduction",Material.BOOK,()->introduction(p,kind,data,branch,page,row)); else if(state.equals("completed")&&!yes(row,"rewardConfigured"))put(screen,31,"Reward policy unavailable","Your objective is verified. Its reward must be configured before claiming.",Material.GRAY_DYE,null); else if(row.has("cooldownUntil")&&!row.get("cooldownUntil").isJsonNull()&&row.get("cooldownUntil").getAsLong()>System.currentTimeMillis())put(screen,31,"Mission cooling down","Available after "+java.time.Instant.ofEpochMilli(row.get("cooldownUntil").getAsLong()),Material.CLOCK,null); else if(yes(row,"canStart")&&!state.equals("active")&&!state.equals("claimed")&&!state.equals("completed"))put(screen,31,"Start mission","Accept this objective through J.A.R.V.I.S.",Material.LIME_DYE,()->act(p,kind,branch,page,row,"start")); else put(screen,31,state.equals("claimed")?"Reward claimed":"Awaiting verified progress","No reward can be issued from an unverified objective",Material.GRAY_DYE,null); if(kind.equals("pol")&&Set.of("POL-ELYTRA-REFINE","POL-ELYTRA-CONTAMINATE").contains(text(row,"id",""))&&(yes(row,"canStart")||Set.of("active","completed","claimed").contains(state)))put(screen,33,"Refine at NPC","Stand near an Arrakis Smuggler.\nTurn in the ingredients shown in this quest.",Material.ORANGE_DYE,()->refine(p,kind,data,branch,page,row)); if(kind.equals("pol")&&row.has("research")&&!state.equals("claimed")&&(yes(row,"canStart")||state.equals("active")||state.equals("completed")))put(screen,33,"Submit research samples","Stand near Gurney Halleck.\nSurrender the materials shown in this quest.",Material.SMITHING_TABLE,()->research(p,kind,branch,page,row)); if(kind.equals("personal")&&(yes(row,"canStart")||Set.of("active","completed","claimed").contains(state))){ if(text(row,"id","").equals("S1-H-01"))put(screen,33,"Collect House T0 kit","Visit Gurney's quartermaster.\nFour Common MK 0 stillsuit pieces at half durability.\nOne Uncommon MK I wooden spice shovel.\nOne original kit per account and season.",Material.NETHERITE_CHESTPLATE,()->starter(p,kind,branch,page,row,"obtain")); if(text(row,"id","").equals("S1-H-02")){put(screen,29,"Prepare four repair parts","Turn in one iron ingot, leather, copper ingot and quartz.\nEach becomes one Uncommon MK I repair component.",Material.IRON_INGOT,()->starter(p,kind,branch,page,row,"parts"));put(screen,33,"Surrender original kit & parts","Hand in the four original bound armour pieces\nand all four prepared parts.\nThen claim this quest to receive the intact kit.",Material.ANVIL,()->starter(p,kind,branch,page,row,"repair"));} } if(row.has("recipe")&&!row.get("recipe").isJsonNull())put(screen,22,"Revealed recipe","Craft on Arrakis · Very Rare · MK XI\nNetherite | Membrane | Netherite\nIron | Diamond | Iron\nContaminated spice | Membrane | Contaminated spice",Material.ELYTRA,null); put(screen,45,"Back","Mission branch",Material.ARROW,()->quests(p,kind,data,branch,page));put(screen,49,"Refresh","Read current progress",Material.CLOCK,()->load(p,kind,branch,text(row,"id",""),page));show(p,screen); } private void refine(Player p,String kind,JsonObject data,String branch,int page,JsonObject row){try{var input=new JsonObject();input.addProperty("action","prepare_refine");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.refinerNpc(p).toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.refineSpice(p,permit);p.sendMessage(Component.text("Spice refined. Your quest receipt is queued for confirmation.",NamedTextColor.GREEN));load(p,kind,branch,text(row,"id",""),page);}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Refinement unavailable. Reopen the quest.":failure.getMessage(),NamedTextColor.RED));}});}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Visit an Arrakis Smuggler first.":failure.getMessage(),NamedTextColor.RED));}} private void research(Player p,String kind,String branch,int page,JsonObject row){try{var input=new JsonObject();input.addProperty("action","prepare_research");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.starterNpc(p).toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.research(p,permit);load(p,kind,branch,text(row,"id",""),page);}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Research receipt pending. Refresh your quest.":failure.getMessage(),NamedTextColor.RED));}});}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Visit Gurney Halleck.":failure.getMessage(),NamedTextColor.RED));}} private void starter(Player p,String kind,String branch,int page,JsonObject row,String operation){try{var input=new JsonObject();input.addProperty("action","prepare_starter");input.addProperty("kind","personal");input.addProperty("definitionId",text(row,"id",""));input.addProperty("operation",operation);input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.starterNpc(p).toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.starterKit(p,permit);load(p,kind,branch,text(row,"id",""),page);}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Your equipment exchange remains available. Reopen the quest.":failure.getMessage(),NamedTextColor.RED));}});}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Visit the quest quartermaster first.":failure.getMessage(),NamedTextColor.RED));}} private void introduction(Player p,String kind,JsonObject data,String branch,int page,JsonObject row){ var screen=panel(p,"Imperial Citizen briefing"); put(screen,13,"Welcome, Imperial Citizen","Your House determines normal travel authority.\nGuild travel uses boarding windows and your central bank.\nClan and company actions follow current deeds.\nBlue missions require ingame actions or item turn-ins.\nWebsite missions use your linked website account.\nRead your Mentat Report for current news and duties.",Material.WRITTEN_BOOK,null); put(screen,30,"I understand","Confirm that you have read this briefing",Material.LIME_DYE,()->{try{bridge.citizenIntroduction(p);p.closeInventory();p.sendMessage(Component.text("Citizen briefing submitted. Refresh your mission journal in a few seconds to claim its verified reward.",NamedTextColor.GREEN));}catch(Exception unavailable){p.sendMessage("The briefing could not be recorded. Please reopen the journal.");}}); put(screen,32,"Back","Return without confirming",Material.ARROW,()->details(p,kind,data,branch,page,row));show(p,screen); } private void act(Player p,String kind,String branch,int page,JsonObject row,String action){var input=new JsonObject();input.addProperty("action",action);input.addProperty("kind",kind);input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("confirmed",true);if(action.equals("claim"))input.add("revision",row.get("revision"));request(p,input,result->{p.sendMessage(Component.text(action.equals("claim")?"Verified quest reward recorded.":"Mission accepted.",NamedTextColor.GREEN));if(action.equals("claim")&&text(row,"id","").equals("S1-H-02"))try{bridge.refreshKits(p);}catch(Exception unavailable){p.sendMessage("Your intact replacement remains queued for delivery.");}load(p,kind,branch,text(row,"id",""),page);});} @EventHandler public void click(InventoryClickEvent e){if(!(e.getView().getTopInventory().getHolder() instanceof Panel panel))return;e.setCancelled(true);if(!(e.getWhoClicked() instanceof Player p)||!panel.owner.equals(p.getUniqueId())||e.getClickedInventory()!=panel.inventory||e.getClick()!=ClickType.LEFT)return;var action=panel.actions.get(e.getRawSlot());if(action!=null&&panel.gate.claim(p.getUniqueId()))Bukkit.getScheduler().runTask(plugin,()->{if(p.isOnline()&&p.getOpenInventory().getTopInventory()==panel.inventory)action.run();});} @EventHandler public void drag(InventoryDragEvent e){if(e.getView().getTopInventory().getHolder() instanceof Panel)e.setCancelled(true);} @EventHandler public void closed(InventoryCloseEvent e){if(e.getInventory().getHolder() instanceof Panel panel)panel.gate.expire();} @EventHandler public void quit(PlayerQuitEvent e){pending.remove(e.getPlayer().getUniqueId());} }