package com.dunerealms.gui; import com.google.gson.JsonObject; import java.math.BigDecimal; import java.util.*; import java.util.function.Consumer; import org.bukkit.*; import org.bukkit.entity.Player; import org.bukkit.event.*; import org.bukkit.event.player.*; import org.bukkit.event.inventory.*; import org.bukkit.inventory.*; import org.bukkit.plugin.java.JavaPlugin; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; /** Arrakis-only presentation. The existing connector checkpoints inventory; * the central bank verifies the receipt and pays from P&O exactly once. */ final class SpiceMenus implements Listener { private final JavaPlugin plugin;private final HouseBridge bridge;private final Consumer back; private final Set busy=new HashSet<>(); private static final class Panel implements DuneMenuInventory{ final UUID owner;final Inventory inventory;final Map actions=new HashMap<>();final GuiSession gate; Panel(Player p){owner=p.getUniqueId();gate=new GuiSession(owner);inventory=Bukkit.createInventory(this,27,Component.text("Arrakis · Spice buyer",NamedTextColor.GOLD));}public Inventory getInventory(){return inventory;} } SpiceMenus(JavaPlugin plugin,HouseBridge bridge,Consumer back){this.plugin=plugin;this.bridge=bridge;this.back=back;Bukkit.getPluginManager().registerEvents(this,plugin);} private static boolean arrakis(Player p){return p.isOnline()&&p.getWorld().getName().equals("arrakis")&&p.getWorld().getEnvironment()==World.Environment.NORMAL;} private static String money(long amount){return BigDecimal.valueOf(amount,2).toPlainString()+" DM";} private static JsonObject action(String name){var q=new JsonObject();q.addProperty("action",name);return q;} private void call(Player p,JsonObject q,Consumer done){ if(!arrakis(p)){p.sendMessage("Spice buyers are available on Arrakis only.");return;}if(!busy.add(p.getUniqueId())){p.sendMessage("Your spice sale is being processed.");return;} Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{JsonObject data=null;String error=null;try{data=bridge.spice(p.getUniqueId(),q);}catch(Exception e){error=e.getMessage();}var result=data;var message=error;if(!plugin.isEnabled())return;Bukkit.getScheduler().runTask(plugin,()->{busy.remove(p.getUniqueId());if(!p.isOnline())return;if(result==null||result.has("rejectedStatus")){p.sendMessage(result!=null&&result.has("message")?result.get("message").getAsString():message==null?"Spice service unavailable. No unconfirmed inventory sale is made; committed sales remain payable.":message);return;}done.accept(result);});}); } void open(Player p){open(p,null);} void open(Player p,String selected){ if(!arrakis(p)){p.sendMessage("Spice buyers are available on Arrakis only.");return;} var panel=new Panel(p);int guildCount,smugglerCount; try{guildCount=bridge.spiceCount(p,"guild");smugglerCount=bridge.spiceCount(p,"smuggler");}catch(Exception e){p.sendMessage("Spice inventory unavailable.");return;} put(panel,4,Material.ORANGE_DYE,"Melange Spice",guildCount+" raw-spice units (1 block = 9)\nP&O pays your personal bank account",null,null); put(panel,11,Material.PLAYER_HEAD,"Sell "+guildCount+" to the Guild","Sell eligible spice at the current authorised rate",()->sellAll(p,"guild",guildCount),"spice_guild"); put(panel,15,Material.PLAYER_HEAD,"Sell "+smugglerCount+" to Esmar Tuek","Contraband only · Requires an active Smuggler quest",()->sellAll(p,"smuggler",smugglerCount),"spice_smuggler"); put(panel,26,Material.GOLD_INGOT,"Collect pending payments","Retry committed P&O spice payments",()->recover(p),null); put(panel,22,Material.ARROW,"Back","Imperial Codex",()->back.accept(p),null);show(p,panel); } void sellAll(Player p,String channel){sellAll(p,channel,null);} private void sellAll(Player p,String channel,Integer expectedCount){ if(!Set.of("guild","smuggler").contains(channel)){p.sendMessage("/sellall [guild|smuggler]");return;}if(!arrakis(p)){p.sendMessage("Spice buyers are available on Arrakis only.");return;} int count;try{count=bridge.spiceCount(p,channel);}catch(Exception e){p.sendMessage("Spice inventory unavailable.");return;} if(expectedCount!=null&&count!=expectedCount){p.sendMessage("Your spice inventory changed. Choose a buyer again.");open(p);return;} sell(p,channel,count); } private void sell(Player p,String channel,int count){if(count<1){p.sendMessage("You have no matching spice for this buyer.");return;}p.closeInventory();var q=action("prepare");UUID request=UUID.randomUUID();q.addProperty("requestId",request.toString());q.addProperty("channel",channel);q.addProperty("amount",count);q.addProperty("confirmed",true); call(p,q,permit->{if(!arrakis(p)){p.sendMessage("Return to Arrakis to sell spice.");return;}try{bridge.sellSpice(p,permit);}catch(Exception e){p.sendMessage(e.getMessage()==null?"Spice sale not confirmed.":e.getMessage());return;}settle(p,request,true);}); } private void settle(Player p,UUID id,boolean notify){var q=action("settle");q.addProperty("requestId",id.toString());call(p,q,data->{if(notify)p.sendMessage("Sold "+data.get("amount").getAsInt()+" Melange Spice. P&O paid "+money(data.get("netMinor").getAsLong())+" to your bank account.");});} @EventHandler public void join(PlayerJoinEvent e){Bukkit.getScheduler().runTaskLater(plugin,()->recover(e.getPlayer()),120);} private void recover(Player p){if(!arrakis(p))return;call(p,action("pending"),data->recoverNext(p,data.getAsJsonArray("pending").asList().stream().map(v->UUID.fromString(v.getAsString())).toList(),0));} private void recoverNext(Player p,List ids,int index){if(index>=ids.size()||!arrakis(p))return;var q=action("settle");q.addProperty("requestId",ids.get(index).toString());call(p,q,data->recoverNext(p,ids,index+1));} private static void put(Panel panel,int slot,Material material,String name,String lore,Runnable action,String art){var item=new ItemStack(material);var meta=item.getItemMeta();meta.displayName(Component.text(name,NamedTextColor.GOLD));meta.lore(Arrays.stream(lore.split("\n")).map(line->Component.text(line,NamedTextColor.GRAY)).toList());if(art!=null)meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","menu_art"),org.bukkit.persistence.PersistentDataType.STRING,art);item.setItemMeta(meta);panel.inventory.setItem(slot,item);if(action!=null)panel.actions.put(slot,action);} private void show(Player p,Panel panel){if(BedrockForms.isBedrock(p)){var choices=panel.actions.entrySet().stream().map(entry->new BedrockForms.Choice(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(panel.inventory.getItem(entry.getKey()).getItemMeta().displayName()),"",entry.getValue())).toList();BedrockForms.show(plugin,p,"Arrakis · Spice buyer","P&O pays your personal bank account",choices);return;}if(!MCGUIMenus.show(p,"Arrakis · Spice buyer","Guild trade and quest-authorised smuggling",panel.inventory,panel.actions,panel.gate))p.openInventory(panel.inventory);} @EventHandler public void click(InventoryClickEvent e){if(!(e.getView().getTopInventory().getHolder() instanceof Panel panel))return;e.setCancelled(true);if(!panel.owner.equals(e.getWhoClicked().getUniqueId()))return;Runnable action=panel.actions.get(e.getRawSlot());if(action!=null&&panel.gate.claim(e.getWhoClicked().getUniqueId()))Bukkit.getScheduler().runTask(plugin,action);} @EventHandler public void drag(InventoryDragEvent e){if(e.getView().getTopInventory().getHolder() instanceof Panel)e.setCancelled(true);} }