77import com .fasterxml .jackson .annotation .JsonProperty ;
88import com .fasterxml .jackson .annotation .JsonRootName ;
99
10+ import javafx .collections .ObservableList ;
1011import seedu .address .commons .exceptions .IllegalValueException ;
1112import seedu .address .model .AddressBook ;
1213import seedu .address .model .ReadOnlyAddressBook ;
1314import seedu .address .model .group .Group ;
15+ import seedu .address .model .group .GroupName ;
1416import seedu .address .model .person .Person ;
1517
1618/**
@@ -21,6 +23,10 @@ class JsonSerializableAddressBook {
2123
2224 public static final String MESSAGE_DUPLICATE_PERSON = "Persons list contains duplicate person(s)." ;
2325 public static final String MESSAGE_DUPLICATE_GROUP = "Groups list contains duplicate group(s)." ;
26+ public static final String MESSAGE_NON_EXISTENT_PERSON_IN_GROUP = "Group %s contains a non-existent person %s" ;
27+ public static final String MESSAGE_NON_EXISTENT_GROUP_IN_PERSON = "Person %s contains a non-existent group %s" ;
28+ public static final String MESSAGE_GROUP_AND_PERSON_CONFLICT =
29+ "Person %s group-list conflict with group %s person-list" ;
2430
2531 private final List <JsonAdaptedPerson > persons = new ArrayList <>();
2632 private final List <JsonAdaptedGroup > groups = new ArrayList <>();
@@ -66,9 +72,46 @@ public AddressBook toModelType() throws IllegalValueException {
6672 if (addressBook .hasGroup (group )) {
6773 throw new IllegalValueException (MESSAGE_DUPLICATE_GROUP );
6874 }
75+ checkExistenceOfPersonsInGroup (group , addressBook .getPersonList ());
6976 addressBook .addGroup (group );
7077 }
78+
79+ for (Person person : addressBook .getPersonList ()) {
80+ checkExistenceOfGroupsInPerson (addressBook , person );
81+ }
82+
7183 return addressBook ;
7284 }
7385
86+ private void checkExistenceOfPersonsInGroup (Group group , ObservableList <Person > globalPersonList )
87+ throws IllegalValueException {
88+ for (Person person : group .getPersons ()) {
89+ if (!globalPersonList .contains (person )) {
90+ throw new IllegalValueException (String .format (MESSAGE_NON_EXISTENT_PERSON_IN_GROUP ,
91+ group .getName (), person ));
92+ }
93+ }
94+ }
95+
96+ private void checkExistenceOfGroupsInPerson (AddressBook addressBook , Person person )
97+ throws IllegalValueException {
98+ for (GroupName groupName : person .getGroups ()) {
99+ if (addressBook .getGroupList ().stream ()
100+ .noneMatch (existingGroup -> existingGroup .getName ().equals (groupName ))) {
101+ throw new IllegalValueException (
102+ String .format (MESSAGE_NON_EXISTENT_GROUP_IN_PERSON , person .getName (), groupName ));
103+ }
104+
105+ for (Group group : addressBook .getGroupList ()) {
106+ if (!group .getName ().equals (groupName )) {
107+ continue ;
108+ }
109+ if (!group .containsPerson (person )) {
110+ throw new IllegalValueException (
111+ String .format (MESSAGE_GROUP_AND_PERSON_CONFLICT , person .getName (), groupName ));
112+ }
113+ }
114+ }
115+ }
116+
74117}
0 commit comments