-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFactionManager.java
More file actions
1167 lines (989 loc) · 37.4 KB
/
Copy pathFactionManager.java
File metadata and controls
1167 lines (989 loc) · 37.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.hyperfactions.manager;
import com.hyperfactions.Permissions;
import com.hyperfactions.api.events.EventBus;
import com.hyperfactions.api.events.FactionDisbandEvent;
import com.hyperfactions.api.events.FactionMemberEvent;
import com.hyperfactions.config.ConfigManager;
import com.hyperfactions.data.*;
import com.hyperfactions.integration.PermissionManager;
import com.hyperfactions.storage.FactionStorage;
import com.hyperfactions.util.Logger;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Manages faction data, membership, and operations.
*/
public class FactionManager {
private final FactionStorage storage;
// Primary cache: faction ID -> Faction
private final Map<UUID, Faction> factions = new ConcurrentHashMap<>();
// Index: player UUID -> faction ID
private final Map<UUID, UUID> playerToFaction = new ConcurrentHashMap<>();
// Index: name (lowercase) -> faction ID
private final Map<String, UUID> nameToFaction = new ConcurrentHashMap<>();
// Announcement callbacks
@Nullable
private BiConsumer<String, String> onFactionCreated;
@Nullable
private TriConsumer<String, String, String> onLeadershipTransferred;
@Nullable
private java.util.function.Consumer<String> onFactionDisbanded;
// Economy callback (fires after faction creation with full Faction object)
@Nullable
private java.util.function.Consumer<Faction> onFactionCreatedForEconomy;
/**
* Functional interface for callbacks with three parameters.
*/
@FunctionalInterface
public interface TriConsumer<A, B, C> {
void accept(A a, B b, C c);
}
/** Creates a new FactionManager. */
public FactionManager(@NotNull FactionStorage storage) {
this.storage = storage;
}
/**
* Sets a callback for when a new faction is created.
* Params: factionName, leaderName
*/
public void setOnFactionCreated(@Nullable BiConsumer<String, String> callback) {
this.onFactionCreated = callback;
}
/**
* Sets a callback for when a faction is created (full Faction object).
* Used by economy module for initialization.
*/
public void setOnFactionCreatedForEconomy(@Nullable java.util.function.Consumer<Faction> callback) {
this.onFactionCreatedForEconomy = callback;
}
/**
* Sets a callback for when leadership is transferred.
* Params: factionName, oldLeaderName, newLeaderName
*/
public void setOnLeadershipTransferred(@Nullable TriConsumer<String, String, String> callback) {
this.onLeadershipTransferred = callback;
}
/**
* Sets a callback for when a faction is disbanded by its leader.
* Not called for admin force-disbands or auto-disbands.
* Param: factionName
*/
public void setOnFactionDisbanded(@Nullable java.util.function.Consumer<String> callback) {
this.onFactionDisbanded = callback;
}
/**
* Loads all factions from storage.
*
* <p>SAFETY: This method will NOT clear existing data if loading fails or returns
* suspiciously empty results when data was expected. This prevents data loss
* from deserialization failures or I/O errors.
*
* @return a future that completes when loading is done
*/
public CompletableFuture<Void> loadAll() {
// Capture current state for safety validation
final int previousFactionCount = factions.size();
final int previousMemberCount = playerToFaction.size();
return storage.loadAllFactions().thenAccept(loaded -> {
// SAFETY CHECK: If we had data before but loading returned nothing,
// this is likely a load failure - DO NOT clear existing data
if (previousFactionCount > 0 && loaded.isEmpty()) {
Logger.severe("CRITICAL: Load returned 0 factions but %d were previously loaded!",
previousFactionCount);
Logger.severe("Keeping existing in-memory data to prevent data loss.");
Logger.severe("Check logs above for deserialization errors. Use '/f admin reload' to retry.");
return;
}
// Build new indices before clearing old ones (atomic swap pattern)
Map<UUID, Faction> newFactions = new HashMap<>();
Map<UUID, UUID> newPlayerToFaction = new HashMap<>();
Map<String, UUID> newNameToFaction = new HashMap<>();
for (Faction faction : loaded) {
newFactions.put(faction.id(), faction);
newNameToFaction.put(faction.name().toLowerCase(), faction.id());
for (UUID memberUuid : faction.members().keySet()) {
newPlayerToFaction.put(memberUuid, faction.id());
}
}
// Now atomically swap the data
factions.clear();
factions.putAll(newFactions);
playerToFaction.clear();
playerToFaction.putAll(newPlayerToFaction);
nameToFaction.clear();
nameToFaction.putAll(newNameToFaction);
Logger.info("[Startup] Loaded %d factions with %d members indexed",
factions.size(), playerToFaction.size());
}).exceptionally(ex -> {
Logger.severe("CRITICAL: Exception during faction loading - keeping existing data", (Throwable) ex);
return null;
});
}
/**
* Saves all factions to storage.
*
* @return a future that completes when saving is done
*/
public CompletableFuture<Void> saveAll() {
List<CompletableFuture<Void>> futures = factions.values().stream()
.map(storage::saveFaction)
.collect(Collectors.toList());
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
}
/**
* Syncs faction data from disk, merging with in-memory data based on timestamps.
* Members with newer lastOnline in memory are kept; members only on disk are added.
* Members removed in-game (not on disk but in memory with newer timestamp) stay removed.
*
* @return a future containing the sync result summary
*/
public CompletableFuture<SyncResult> syncFromDisk() {
return storage.loadAllFactions().thenApply(diskFactions -> {
int factionsUpdated = 0;
int membersAdded = 0;
int membersUpdated = 0;
Map<UUID, Faction> diskFactionMap = new HashMap<>();
for (Faction f : diskFactions) {
diskFactionMap.put(f.id(), f);
}
for (Faction diskFaction : diskFactions) {
Faction memoryFaction = factions.get(diskFaction.id());
if (memoryFaction == null) {
// New faction from disk - add it
factions.put(diskFaction.id(), diskFaction);
nameToFaction.put(diskFaction.name().toLowerCase(), diskFaction.id());
for (UUID memberUuid : diskFaction.members().keySet()) {
playerToFaction.put(memberUuid, diskFaction.id());
}
factionsUpdated++;
membersAdded += diskFaction.members().size();
} else {
// Existing faction - merge members
Map<UUID, FactionMember> mergedMembers = new HashMap<>(memoryFaction.members());
boolean changed = false;
for (FactionMember diskMember : diskFaction.members().values()) {
FactionMember memoryMember = memoryFaction.members().get(diskMember.uuid());
if (memoryMember == null) {
// Member exists on disk but not in memory - add them
mergedMembers.put(diskMember.uuid(), diskMember);
playerToFaction.put(diskMember.uuid(), diskFaction.id());
membersAdded++;
changed = true;
} else if (diskMember.lastOnline() > memoryMember.lastOnline()) {
// Disk has newer data - use disk version
mergedMembers.put(diskMember.uuid(), diskMember);
membersUpdated++;
changed = true;
}
// If memory has newer or equal lastOnline, keep memory version
}
if (changed) {
Faction updated = new Faction(
memoryFaction.id(),
memoryFaction.name(),
memoryFaction.description(),
memoryFaction.tag(),
memoryFaction.color(),
memoryFaction.createdAt(),
memoryFaction.home(),
mergedMembers,
memoryFaction.claims(),
memoryFaction.relations(),
memoryFaction.logs(),
memoryFaction.open(),
memoryFaction.permissions()
);
factions.put(updated.id(), updated);
factionsUpdated++;
}
}
}
Logger.info("[Sync] Sync complete: %d factions updated, %d members added, %d members updated",
factionsUpdated, membersAdded, membersUpdated);
return new SyncResult(factionsUpdated, membersAdded, membersUpdated);
});
}
/**
* Result of a sync operation.
*/
public record SyncResult(int factionsUpdated, int membersAdded, int membersUpdated) {}
// === Faction Queries ===
/**
* Gets a faction by its ID.
*
* @param factionId the faction ID
* @return the faction, or null if not found
*/
@Nullable
public Faction getFaction(@NotNull UUID factionId) {
return factions.get(factionId);
}
/**
* Gets a faction by name (case-insensitive).
*
* @param name the faction name
* @return the faction, or null if not found
*/
@Nullable
public Faction getFactionByName(@NotNull String name) {
UUID id = nameToFaction.get(name.toLowerCase());
return id != null ? factions.get(id) : null;
}
/**
* Gets a faction by tag (case-insensitive).
*
* @param tag the faction tag
* @return the faction, or null if not found
*/
@Nullable
public Faction getFactionByTag(@NotNull String tag) {
String lowerTag = tag.toLowerCase();
return factions.values().stream()
.filter(f -> f.tag() != null && f.tag().equalsIgnoreCase(lowerTag))
.findFirst()
.orElse(null);
}
/**
* Gets a player's faction.
*
* @param playerUuid the player's UUID
* @return the faction, or null if not in one
*/
@Nullable
public Faction getPlayerFaction(@NotNull UUID playerUuid) {
UUID factionId = playerToFaction.get(playerUuid);
return factionId != null ? factions.get(factionId) : null;
}
/**
* Gets a player's faction ID.
*
* @param playerUuid the player's UUID
* @return the faction ID, or null if not in one
*/
@Nullable
public UUID getPlayerFactionId(@NotNull UUID playerUuid) {
return playerToFaction.get(playerUuid);
}
/**
* Checks if a player is in any faction.
*
* @param playerUuid the player's UUID
* @return true if in a faction
*/
public boolean isInFaction(@NotNull UUID playerUuid) {
return playerToFaction.containsKey(playerUuid);
}
/**
* Checks if two players are in the same faction.
*
* @param player1 first player's UUID
* @param player2 second player's UUID
* @return true if same faction
*/
public boolean areInSameFaction(@NotNull UUID player1, @NotNull UUID player2) {
UUID f1 = playerToFaction.get(player1);
UUID f2 = playerToFaction.get(player2);
return f1 != null && f1.equals(f2);
}
/**
* Checks if a faction name is taken.
*
* @param name the name to check
* @return true if taken
*/
public boolean isNameTaken(@NotNull String name) {
return nameToFaction.containsKey(name.toLowerCase());
}
/**
* Gets all factions.
*
* @return collection of all factions
*/
@NotNull
public Collection<Faction> getAllFactions() {
return Collections.unmodifiableCollection(factions.values());
}
/**
* Gets faction count.
*
* @return number of factions
*/
public int getFactionCount() {
return factions.size();
}
// === Faction Operations ===
/**
* Result of a faction operation.
*/
public enum FactionResult {
SUCCESS,
ALREADY_IN_FACTION,
NOT_IN_FACTION,
FACTION_NOT_FOUND,
NAME_TAKEN,
NAME_TOO_SHORT,
NAME_TOO_LONG,
FACTION_FULL,
NOT_LEADER,
NOT_OFFICER,
CANNOT_KICK_LEADER,
CANNOT_DEMOTE_MEMBER,
CANNOT_PROMOTE_LEADER,
TARGET_NOT_IN_FACTION,
NO_PERMISSION
}
/**
* Creates a new faction.
*
* @param name the faction name
* @param leaderUuid the leader's UUID
* @param leaderName the leader's username
* @return the result
*/
public FactionResult createFaction(@NotNull String name, @NotNull UUID leaderUuid, @NotNull String leaderName) {
// Check permission first
if (!PermissionManager.get().hasPermission(leaderUuid, Permissions.CREATE)) {
return FactionResult.NO_PERMISSION;
}
// Validation
if (isInFaction(leaderUuid)) {
return FactionResult.ALREADY_IN_FACTION;
}
ConfigManager config = ConfigManager.get();
if (name.length() < config.getMinNameLength()) {
return FactionResult.NAME_TOO_SHORT;
}
if (name.length() > config.getMaxNameLength()) {
return FactionResult.NAME_TOO_LONG;
}
if (isNameTaken(name)) {
return FactionResult.NAME_TAKEN;
}
// Create faction with auto-generated tag
Faction faction = Faction.create(name, leaderUuid, leaderName);
String generatedTag = generateUniqueTag(name);
faction = faction.withTag(generatedTag);
// Update caches
factions.put(faction.id(), faction);
nameToFaction.put(name.toLowerCase(), faction.id());
playerToFaction.put(leaderUuid, faction.id());
// Save async
storage.saveFaction(faction);
// Publish member join event for the creator (so membership history is recorded)
EventBus.publish(new FactionMemberEvent(faction, leaderUuid, FactionMemberEvent.Type.JOIN));
Logger.info("[Faction] Faction '%s' [%s] created by %s", name, generatedTag, leaderName);
if (onFactionCreated != null) {
try {
onFactionCreated.accept(name, leaderName);
} catch (Exception e) {
Logger.warn("Error in faction created callback: %s", e.getMessage());
}
}
if (onFactionCreatedForEconomy != null) {
try {
onFactionCreatedForEconomy.accept(faction);
} catch (Exception e) {
Logger.warn("Error in economy creation callback: %s", e.getMessage());
}
}
return FactionResult.SUCCESS;
}
/**
* Generates a unique faction tag from the faction name.
* Takes first 3 alphanumeric characters (uppercase), appends numbers if collision exists.
*
* @param factionName the faction name to generate a tag from
* @return a unique tag (1-5 chars)
*/
@NotNull
public String generateUniqueTag(@NotNull String factionName) {
// Extract alphanumeric characters only, uppercase
StringBuilder baseBuilder = new StringBuilder();
for (char c : factionName.toCharArray()) {
if (Character.isLetterOrDigit(c)) {
baseBuilder.append(Character.toUpperCase(c));
if (baseBuilder.length() >= 3) {
break;
}
}
}
// Ensure at least 1 character
if (baseBuilder.isEmpty()) {
baseBuilder.append("F"); // Fallback to 'F' for Faction
}
String baseTag = baseBuilder.toString();
// Check if base tag is unique
if (getFactionByTag(baseTag) == null) {
return baseTag;
}
// Append numbers until unique (max 5 chars total)
for (int suffix = 2; suffix <= 99; suffix++) {
String candidate = baseTag + suffix;
if (candidate.length() > 5) {
// Shorten base to make room for suffix
int maxBaseLen = 5 - String.valueOf(suffix).length();
candidate = baseTag.substring(0, Math.min(baseTag.length(), maxBaseLen)) + suffix;
}
if (getFactionByTag(candidate) == null) {
return candidate;
}
}
// Fallback: random suffix (very unlikely to reach here)
return baseTag.substring(0, Math.min(baseTag.length(), 2)) + UUID.randomUUID().toString().substring(0, 3).toUpperCase();
}
/**
* Disbands a faction.
*
* @param factionId the faction ID
* @param actorUuid the actor's UUID (must be leader)
* @return the result
*/
public FactionResult disbandFaction(@NotNull UUID factionId, @NotNull UUID actorUuid) {
// Check permission first
if (!PermissionManager.get().hasPermission(actorUuid, Permissions.DISBAND)) {
return FactionResult.NO_PERMISSION;
}
Faction faction = factions.get(factionId);
if (faction == null) {
return FactionResult.FACTION_NOT_FOUND;
}
// Check if actor is leader
FactionMember actor = faction.getMember(actorUuid);
if (actor == null || !actor.isLeader()) {
return FactionResult.NOT_LEADER;
}
// Remove from caches
factions.remove(factionId);
nameToFaction.remove(faction.name().toLowerCase());
for (UUID memberUuid : faction.members().keySet()) {
playerToFaction.remove(memberUuid);
}
// Delete from storage
storage.deleteFaction(factionId);
// Fire event so listeners can clean up claims, relations, etc.
EventBus.publish(new FactionDisbandEvent(faction, actorUuid));
Logger.info("[Faction] Faction '%s' disbanded", faction.name());
if (onFactionDisbanded != null) {
try {
onFactionDisbanded.accept(faction.name());
} catch (Exception e) {
Logger.warn("Error in faction disbanded callback: %s", e.getMessage());
}
}
return FactionResult.SUCCESS;
}
/**
* Adds a member to a faction.
*
* @param factionId the faction ID
* @param playerUuid the player's UUID
* @param playerName the player's username
* @return the result
*/
public FactionResult addMember(@NotNull UUID factionId, @NotNull UUID playerUuid, @NotNull String playerName) {
Faction faction = factions.get(factionId);
if (faction == null) {
return FactionResult.FACTION_NOT_FOUND;
}
if (isInFaction(playerUuid)) {
return FactionResult.ALREADY_IN_FACTION;
}
if (faction.getMemberCount() >= ConfigManager.get().getMaxMembers()) {
return FactionResult.FACTION_FULL;
}
// Add member
FactionMember member = FactionMember.create(playerUuid, playerName);
Faction updated = faction.withMember(member)
.withLog(FactionLog.create(FactionLog.LogType.MEMBER_JOIN, playerName + " joined the faction", playerUuid));
// Update caches
factions.put(factionId, updated);
playerToFaction.put(playerUuid, factionId);
// Save async
storage.saveFaction(updated);
// Publish member join event
EventBus.publish(new FactionMemberEvent(updated, playerUuid, FactionMemberEvent.Type.JOIN));
return FactionResult.SUCCESS;
}
/**
* Removes a member from a faction.
* If the leader leaves and other members exist, promotes the highest-ranked member with most tenure.
* If the leader leaves and no other members exist, disbands the faction.
*
* @param factionId the faction ID
* @param playerUuid the player's UUID
* @param actorUuid the actor's UUID (self for leaving, officer+ for kicking)
* @param isKick true if this is a kick, false if leaving
* @return the result
*/
public FactionResult removeMember(@NotNull UUID factionId, @NotNull UUID playerUuid,
@NotNull UUID actorUuid, boolean isKick) {
Faction faction = factions.get(factionId);
if (faction == null) {
return FactionResult.FACTION_NOT_FOUND;
}
FactionMember target = faction.getMember(playerUuid);
if (target == null) {
return FactionResult.TARGET_NOT_IN_FACTION;
}
// Handle leader removal with succession
if (target.isLeader()) {
// Find successor
FactionMember successor = faction.findSuccessor();
if (successor == null) {
// No other members - disband the faction
return disbandFactionInternal(factionId, "Leader left with no remaining members");
}
// Promote successor to leader
FactionMember promoted = successor.withRole(FactionRole.LEADER);
Faction updated = faction
.withoutMember(playerUuid)
.withMember(promoted)
.withLog(FactionLog.create(FactionLog.LogType.LEADER_TRANSFER,
target.username() + " left, " + promoted.username() + " is now leader", playerUuid));
factions.put(factionId, updated);
playerToFaction.remove(playerUuid);
storage.saveFaction(updated);
// Publish member leave event
EventBus.publish(new FactionMemberEvent(updated, playerUuid, FactionMemberEvent.Type.LEAVE));
Logger.info("[Faction] Leader %s left faction '%s', %s promoted to leader",
target.username(), faction.name(), promoted.username());
if (onLeadershipTransferred != null) {
try {
onLeadershipTransferred.accept(faction.name(), target.username(), promoted.username());
} catch (Exception e) {
Logger.warn("Error in leadership transferred callback: %s", e.getMessage());
}
}
return FactionResult.SUCCESS;
}
// If kicking (non-leader), check permissions
if (isKick && !actorUuid.equals(playerUuid)) {
FactionMember actor = faction.getMember(actorUuid);
if (actor == null || !actor.role().canManage(target.role())) {
return FactionResult.NOT_OFFICER;
}
}
// Remove member
FactionLog.LogType logType = isKick ? FactionLog.LogType.MEMBER_KICK : FactionLog.LogType.MEMBER_LEAVE;
String message = isKick ? target.username() + " was kicked" : target.username() + " left the faction";
Faction updated = faction.withoutMember(playerUuid)
.withLog(FactionLog.create(logType, message, actorUuid));
// Update caches
factions.put(factionId, updated);
playerToFaction.remove(playerUuid);
// Save async
storage.saveFaction(updated);
// Publish member leave/kick event
FactionMemberEvent.Type eventType = isKick ? FactionMemberEvent.Type.KICK : FactionMemberEvent.Type.LEAVE;
EventBus.publish(new FactionMemberEvent(updated, playerUuid, eventType));
return FactionResult.SUCCESS;
}
/**
* Disbands a faction internally (system-initiated).
* Used when leader leaves with no remaining members, or for ban-triggered dissolution.
*
* @param factionId the faction ID
* @param reason the reason for disbanding (logged)
* @return the result
*/
private FactionResult disbandFactionInternal(@NotNull UUID factionId, @NotNull String reason) {
Faction faction = factions.get(factionId);
if (faction == null) {
return FactionResult.FACTION_NOT_FOUND;
}
// Get leader UUID for event (use first found, or null for system-initiated)
UUID disbandedBy = faction.getLeader() != null ? faction.getLeader().uuid() : null;
// Remove from caches
factions.remove(factionId);
nameToFaction.remove(faction.name().toLowerCase());
for (UUID memberUuid : faction.members().keySet()) {
playerToFaction.remove(memberUuid);
}
// Delete from storage
storage.deleteFaction(factionId);
// Fire event so listeners can clean up claims, relations, etc.
EventBus.publish(new FactionDisbandEvent(faction, disbandedBy));
Logger.info("[Faction] Faction '%s' disbanded: %s", faction.name(), reason);
return FactionResult.SUCCESS;
}
/**
* Force disbands a faction without permission checks.
* Used for admin operations and data imports.
*
* @param factionId the faction ID
* @param reason the reason for disbanding (logged)
* @return the result
*/
public FactionResult forceDisband(@NotNull UUID factionId, @NotNull String reason) {
return disbandFactionInternal(factionId, reason);
}
/**
* Promotes a member to the next rank.
*
* @param factionId the faction ID
* @param playerUuid the player's UUID to promote
* @param actorUuid the actor's UUID
* @return the result
*/
public FactionResult promoteMember(@NotNull UUID factionId, @NotNull UUID playerUuid, @NotNull UUID actorUuid) {
// Check permission first
if (!PermissionManager.get().hasPermission(actorUuid, Permissions.PROMOTE)) {
return FactionResult.NO_PERMISSION;
}
Faction faction = factions.get(factionId);
if (faction == null) {
return FactionResult.FACTION_NOT_FOUND;
}
FactionMember actor = faction.getMember(actorUuid);
if (actor == null || !actor.isLeader()) {
return FactionResult.NOT_LEADER;
}
FactionMember target = faction.getMember(playerUuid);
if (target == null) {
return FactionResult.TARGET_NOT_IN_FACTION;
}
// Can't promote a leader
if (target.role() == FactionRole.LEADER) {
return FactionResult.CANNOT_PROMOTE_LEADER;
}
// Promote to next rank
FactionRole newRole = target.role() == FactionRole.MEMBER ? FactionRole.OFFICER : FactionRole.LEADER;
FactionMember promoted = target.withRole(newRole);
Faction updated = faction.withMember(promoted)
.withLog(FactionLog.create(FactionLog.LogType.MEMBER_PROMOTE,
target.username() + " promoted to " + ConfigManager.get().getRoleDisplayName(newRole), actorUuid));
factions.put(factionId, updated);
storage.saveFaction(updated);
// Publish promote event
EventBus.publish(new FactionMemberEvent(updated, playerUuid, FactionMemberEvent.Type.PROMOTE));
return FactionResult.SUCCESS;
}
/**
* Demotes a member to the previous rank.
*
* @param factionId the faction ID
* @param playerUuid the player's UUID to demote
* @param actorUuid the actor's UUID
* @return the result
*/
public FactionResult demoteMember(@NotNull UUID factionId, @NotNull UUID playerUuid, @NotNull UUID actorUuid) {
// Check permission first
if (!PermissionManager.get().hasPermission(actorUuid, Permissions.DEMOTE)) {
return FactionResult.NO_PERMISSION;
}
Faction faction = factions.get(factionId);
if (faction == null) {
return FactionResult.FACTION_NOT_FOUND;
}
FactionMember actor = faction.getMember(actorUuid);
if (actor == null || !actor.isLeader()) {
return FactionResult.NOT_LEADER;
}
FactionMember target = faction.getMember(playerUuid);
if (target == null) {
return FactionResult.TARGET_NOT_IN_FACTION;
}
// Can't demote a member (already lowest)
if (target.role() == FactionRole.MEMBER) {
return FactionResult.CANNOT_DEMOTE_MEMBER;
}
// Demote
FactionMember demoted = target.withRole(FactionRole.MEMBER);
Faction updated = faction.withMember(demoted)
.withLog(FactionLog.create(FactionLog.LogType.MEMBER_DEMOTE,
target.username() + " demoted to " + ConfigManager.get().getRoleDisplayName(FactionRole.MEMBER), actorUuid));
factions.put(factionId, updated);
storage.saveFaction(updated);
// Publish demote event
EventBus.publish(new FactionMemberEvent(updated, playerUuid, FactionMemberEvent.Type.DEMOTE));
return FactionResult.SUCCESS;
}
/**
* Transfers leadership to another member.
*
* @param factionId the faction ID
* @param newLeader the new leader's UUID
* @param actorUuid the current leader's UUID
* @return the result
*/
public FactionResult transferLeadership(@NotNull UUID factionId, @NotNull UUID newLeader, @NotNull UUID actorUuid) {
// Check permission first
if (!PermissionManager.get().hasPermission(actorUuid, Permissions.TRANSFER)) {
return FactionResult.NO_PERMISSION;
}
Faction faction = factions.get(factionId);
if (faction == null) {
return FactionResult.FACTION_NOT_FOUND;
}
FactionMember actor = faction.getMember(actorUuid);
if (actor == null || !actor.isLeader()) {
return FactionResult.NOT_LEADER;
}
FactionMember target = faction.getMember(newLeader);
if (target == null) {
return FactionResult.TARGET_NOT_IN_FACTION;
}
// Demote old leader, promote new leader
FactionMember oldLeader = actor.withRole(FactionRole.OFFICER);
FactionMember promoted = target.withRole(FactionRole.LEADER);
Faction updated = faction
.withMember(oldLeader)
.withMember(promoted)
.withLog(FactionLog.create(FactionLog.LogType.LEADER_TRANSFER,
"Leadership transferred to " + target.username(), actorUuid));
factions.put(factionId, updated);
storage.saveFaction(updated);
Logger.info("[Faction] Faction '%s' leadership transferred to %s", faction.name(), target.username());
if (onLeadershipTransferred != null) {
try {
onLeadershipTransferred.accept(faction.name(), actor.username(), target.username());
} catch (Exception e) {
Logger.warn("Error in leadership transferred callback: %s", e.getMessage());
}
}
return FactionResult.SUCCESS;
}
/**
* Admin: Sets a member's role without permission checks.
* Handles leader transfers automatically.
*
* @param factionId the faction ID
* @param playerUuid the player's UUID
* @param newRole the new role
* @return the result
*/
public FactionResult adminSetMemberRole(@NotNull UUID factionId, @NotNull UUID playerUuid, @NotNull FactionRole newRole) {
Faction faction = factions.get(factionId);
if (faction == null) {
return FactionResult.FACTION_NOT_FOUND;
}
FactionMember target = faction.getMember(playerUuid);
if (target == null) {
return FactionResult.TARGET_NOT_IN_FACTION;
}
// If promoting to leader, demote current leader
Faction updated = faction;
if (newRole == FactionRole.LEADER && target.role() != FactionRole.LEADER) {
FactionMember currentLeader = faction.getLeader();
if (currentLeader != null && !currentLeader.uuid().equals(playerUuid)) {
FactionMember demotedLeader = currentLeader.withRole(FactionRole.OFFICER);
updated = updated.withMember(demotedLeader);
}
}
// Update target's role
FactionMember updatedMember = target.withRole(newRole);
updated = updated.withMember(updatedMember)
.withLog(FactionLog.create(FactionLog.LogType.MEMBER_PROMOTE,
"[Admin] " + target.username() + " role set to " + ConfigManager.get().getRoleDisplayName(newRole), null));
factions.put(factionId, updated);
storage.saveFaction(updated);
Logger.info("[Admin] Set %s role to %s in faction '%s'",
target.username(), ConfigManager.get().getRoleDisplayName(newRole), faction.name());
return FactionResult.SUCCESS;
}
/**
* Admin: Removes a member without permission checks.
* Cannot remove leaders (must demote first or disband).
*
* @param factionId the faction ID
* @param playerUuid the player's UUID
* @return the result
*/
public FactionResult adminRemoveMember(@NotNull UUID factionId, @NotNull UUID playerUuid) {
Faction faction = factions.get(factionId);
if (faction == null) {
return FactionResult.FACTION_NOT_FOUND;
}
FactionMember target = faction.getMember(playerUuid);
if (target == null) {
return FactionResult.TARGET_NOT_IN_FACTION;
}
// Can't kick the leader - must demote or disband
if (target.role() == FactionRole.LEADER) {
return FactionResult.CANNOT_KICK_LEADER;
}
// Remove member
Faction updated = faction.withoutMember(playerUuid)
.withLog(FactionLog.create(FactionLog.LogType.MEMBER_KICK,
"[Admin] " + target.username() + " was kicked", null));
factions.put(factionId, updated);
playerToFaction.remove(playerUuid);
storage.saveFaction(updated);
// Publish kick event (so membership history is recorded)
EventBus.publish(new FactionMemberEvent(updated, playerUuid, FactionMemberEvent.Type.KICK));
Logger.info("[Admin] Kicked %s from faction '%s'", target.username(), faction.name());
return FactionResult.SUCCESS;
}
/**
* Updates a faction's home.
*
* @param factionId the faction ID
* @param home the new home, or null to clear
* @param actorUuid the actor's UUID
* @return the result
*/
public FactionResult setHome(@NotNull UUID factionId, @Nullable Faction.FactionHome home, @NotNull UUID actorUuid) {
// Check permission first
if (!PermissionManager.get().hasPermission(actorUuid, Permissions.SETHOME)) {
return FactionResult.NO_PERMISSION;
}
Faction faction = factions.get(factionId);
if (faction == null) {
return FactionResult.FACTION_NOT_FOUND;
}
FactionMember actor = faction.getMember(actorUuid);
if (actor == null || !actor.isOfficerOrHigher()) {
return FactionResult.NOT_OFFICER;
}
Faction updated = faction.withHome(home)
.withLog(FactionLog.create(FactionLog.LogType.HOME_SET,