package com.dunerealms.gui; import com.google.gson.*; import java.util.*; import java.util.function.Consumer; 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; /** One team muster view. All roster/key/launch authority lives in the shared war exchange. */ final class WarMenus implements Listener { private final JavaPlugin plugin;private final HouseBridge bridge;private final Set pending=new HashSet<>(); private static final int[] SLOTS={19,20,21,22,28,29,30,31}; private static final class Panel implements InventoryHolder { final UUID owner;final GuiSession gate;final Inventory inventory;final String title,baseDescription;String description;final Map actions=new HashMap<>();final List choices=new ArrayList<>(); Panel(Player p,String title,String description){owner=p.getUniqueId();gate=new GuiSession(owner);this.title=title;this.baseDescription=description;this.description=description;inventory=Bukkit.createInventory(this,54,Component.text(title,NamedTextColor.GOLD));var fill=new ItemStack(Material.GRAY_STAINED_GLASS_PANE);var meta=fill.getItemMeta();meta.displayName(Component.empty());fill.setItemMeta(meta);for(int i=0;i<54;i++)inventory.setItem(i,fill);} public Inventory getInventory(){return inventory;} } WarMenus(JavaPlugin plugin,HouseBridge bridge){this.plugin=plugin;this.bridge=bridge;Bukkit.getPluginManager().registerEvents(this,plugin);} private static String text(JsonObject v,String key,String fallback){return v.has(key)&&!v.get(key).isJsonNull()?v.get(key).getAsString():fallback;} private static boolean yes(JsonObject v,String key){return v.has(key)&&!v.get(key).isJsonNull()&&v.get(key).getAsBoolean();} private void put(Panel p,int slot,String title,String body,Material material,Runnable action){var item=new ItemStack(material);var meta=item.getItemMeta();meta.displayName(Component.text(title,NamedTextColor.GOLD));meta.lore(Arrays.stream(body.split("\n")).map(x->Component.text(x,NamedTextColor.GRAY)).toList());item.setItemMeta(meta);p.inventory.setItem(slot,item);if(action!=null){p.actions.put(slot,action);p.choices.add(new BedrockForms.Choice(title,body,action));}else p.description+="\n\n"+title+"\n"+body;} private void show(Player p,Panel panel){if(BedrockForms.isBedrock(p)){BedrockForms.show(plugin,p,panel.title,panel.description,List.copyOf(panel.choices));return;}if(MCGUIMenus.show(p,panel.title,panel.title.equals("War Muster Room")?panel.baseDescription:panel.description,panel.inventory,panel.actions,panel.gate))return;p.openInventory(panel.inventory);Bukkit.getScheduler().runTaskLater(plugin,panel.gate::expire,2400L);} private void request(Player p,JsonObject input,Consumer result){UUID id=p.getUniqueId(),world=p.getWorld().getUID();if(!pending.add(id))return;p.closeInventory();Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{JsonObject data=null;String error=null;try{data=bridge.warMuster(id,input);}catch(Exception e){error=e instanceof java.io.IOException?e.getMessage():"War muster is temporarily unavailable.";}JsonObject received=data;String message=error;if(!plugin.isEnabled())return;Bukkit.getScheduler().runTask(plugin,()->{pending.remove(id);if(!p.isOnline()||!world.equals(p.getWorld().getUID()))return;if(message!=null){p.sendMessage(message);return;}if(received==null||!yes(received,"ok")){p.sendMessage(received==null?"War muster unavailable.":text(received,"message","War muster unavailable."));return;}result.accept(received);});});} void open(Player p){var in=new JsonObject();in.addProperty("action","read");request(p,in,data->{var wars=data.getAsJsonArray("wars");if(wars.size()==1){var row=wars.get(0).getAsJsonObject();muster(p,row,selected(row));return;}var screen=new Panel(p,"War Marshal","Clan warfare · 8 players per side. Larger wars are administered on the website.");int slot=10;for(var entry:wars){if(slot>=45)break;var row=entry.getAsJsonObject();put(screen,slot++,text(row,"title","Clan war"),"War ID: "+text(row,"warId","")+"\nOpen your team muster.",Material.FILLED_MAP,()->muster(p,row,selected(row)));}if(wars.isEmpty())put(screen,22,"No current clan war","Agree a war and calendar hour in the website War Exchange first.",Material.MAP,null);put(screen,49,"War Exchange","Open the existing website War Exchange",Material.WRITABLE_BOOK,()->{p.closeInventory();p.sendMessage(Component.text("Open War Exchange →",NamedTextColor.GOLD).clickEvent(ClickEvent.openUrl("https://www.dunerealms.com/government.html")));});show(p,screen);});} private static List selected(JsonObject row){List result=new ArrayList<>();for(var e:row.getAsJsonArray("selected"))result.add(e.getAsString());while(result.size()<8)result.add(null);return result;} private static JsonObject member(JsonObject row,String id){if(id!=null)for(var e:row.getAsJsonArray("candidates")){var m=e.getAsJsonObject();if(id.equals(text(m,"uuid","")))return m;}return null;} private static String home(JsonObject team){if(!team.has("homeBlock")||team.get("homeBlock").isJsonNull())return "Home Block pending";var block=team.getAsJsonObject("homeBlock");var pos=block.getAsJsonObject("position");return text(team,"homeServer","")+" · "+pos.get("x").getAsInt()+", "+pos.get("z").getAsInt();} private JsonObject action(JsonObject row,String name){var input=new JsonObject();input.addProperty("action",name);input.addProperty("warId",text(row,"warId",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("revision",row.get("revision").getAsLong());input.add("party",row.getAsJsonObject("party").deepCopy());return input;} private void muster(Player p,JsonObject row,List draft){String schedule=row.has("block")&&!row.get("block").isJsonNull()?"Scheduled: "+java.time.format.DateTimeFormatter.ofPattern("dd MMM HH:mm 'UTC'").withZone(java.time.ZoneOffset.UTC).format(java.time.Instant.ofEpochMilli(row.getAsJsonObject("block").get("startsAt").getAsLong())):"Calendar agreement pending";var screen=new Panel(p,"War Muster Room",text(row,"title","Clan War")+"\n"+schedule+" · 8 vs 8\nWar ID: "+text(row,"warId","")+"\nSave writes directly to the website.");int slot=2;for(var e:row.getAsJsonArray("teams")){var team=e.getAsJsonObject();boolean own=text(team,"partyKey","").equals(text(row,"partyKey",""));String color=text(team,"color","");put(screen,slot,""+color+" · "+text(team,"name","Team"),(own?"Your team":"Opposing team · read only")+"\n"+team.get("count").getAsInt()+" / "+team.get("capacity").getAsInt()+"\nProvince: "+home(team),color.equals("Blue")?Material.BLUE_BANNER:Material.RED_BANNER,null);slot+=4;} var edit=yes(row,"editable");for(int i=0;ichoose(p,row,draft,index,0):null);} if(row.has("invite")&&!row.get("invite").isJsonNull()){var key=row.getAsJsonObject("invite");String code=text(key,"code","");put(screen,34,"Team roster key",code.isEmpty()?"This key is closed or all slots are filled.":code+"\nShare only with eligible guests. They type /rosterkey "+code+" in chat.",Material.TRIPWIRE_HOOK,null);}else put(screen,34,"Team roster key","Save once to obtain your team's single invite key.",Material.TRIPWIRE_HOOK,null); put(screen,45,"Back","War Marshal",Material.ARROW,()->open(p));put(screen,47,"Refresh","Reload the authoritative roster and status",Material.COMPASS,()->open(p));if(edit)put(screen,49,"Save roster","Write your selected players directly to the shared war roster.",Material.EMERALD,()->{var in=action(row,"save");var players=new JsonArray();for(String id:draft)if(id!=null)players.add(id);in.add("players",players);request(p,in,data->{p.sendMessage("Roster saved to the website.");open(p);});});if(yes(row,"canLaunch"))put(screen,51,"Launch War","Both teams are full and the agreed hour has begun. Either leader can launch.",Material.NETHERITE_SWORD,()->request(p,action(row,"launch"),data->{p.sendMessage("War launched.");open(p);}));else put(screen,51,"Launch War",yes(row,"launched")?"Already launched.":"At the agreed hour, both teams must be full for manual launch. Otherwise the automatic launch is attempted 15 minutes later.",Material.CLOCK,null);show(p,screen);} private void choose(Player p,JsonObject row,List draft,int index,int page){var screen=new Panel(p,"Choose team member","Slot "+(index+1)+" · current eligible players only");List candidates=new ArrayList<>();for(var entry:row.getAsJsonArray("candidates")){var m=entry.getAsJsonObject();String id=text(m,"uuid","");if(!draft.contains(id)||id.equals(draft.get(index)))candidates.add(m);}for(int i=page*36;i{draft.set(index,id);muster(p,row,draft);});}put(screen,45,"Back","Keep the current draft",Material.ARROW,()->muster(p,row,draft));put(screen,49,"Clear slot","Leave room for a team guest",Material.BARRIER,()->{draft.set(index,null);muster(p,row,draft);});if(page>0)put(screen,47,"Previous page","More candidates",Material.ARROW,()->choose(p,row,draft,index,page-1));if((page+1)*36choose(p,row,draft,index,page+1));show(p,screen);} void accept(Player p,String code){var input=new JsonObject();input.addProperty("action","join");input.addProperty("code",code);request(p,input,data->p.sendMessage("War roster joined: "+text(data,"team","Team")+" · "+text(data,"warId","")));} @EventHandler public void clicked(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 dragged(InventoryDragEvent e){if(e.getView().getTopInventory().getHolder() instanceof Panel)e.setCancelled(true);} @EventHandler public void quit(PlayerQuitEvent e){pending.remove(e.getPlayer().getUniqueId());} }