001package Torello.Browser.JsonAST;
002
003import Torello.JSON.ReadJSON;
004import Torello.JSON.RJArrIntoStream;
005
006import Torello.Java.ReadOnly.ReadOnlyList;
007import Torello.Java.ReadOnly.ReadOnlyArrayList;
008
009import javax.json.JsonArray;
010import javax.json.JsonObject;
011
012/**
013 * This checks for a Json Propety having the name {@code "enum"}.  If such a property does exists,
014 * it's contents are extracted and converted into a {@link ReadOnlyList ReadOnlyList<String>}, and 
015 * returned to the caller. 
016 */
017@Torello.JavaDoc.Annotations.StaticFunctional
018@Torello.JavaDoc.Annotations.JDHeaderBackgroundImg(EmbedTagFileID="CONSTRUCTOR_JDHBI")
019public class Helper$Enum
020{
021    private Helper$Enum() { }
022
023    static ReadOnlyList<String> getEnumPropertyOrNull(final Entity THIS, final JsonObject jo)
024    {
025        // getJsonArray(JsonObject jo, String propertyName, boolean isOptional, boolean throwOnNull)
026        final JsonArray enumArr = ReadJSON.getJsonArray(jo, "enum", true, true);
027
028        if (enumArr == null) return null;
029
030        final ReadOnlyList<String> enumVals = RJArrIntoStream 
031            // strArr(JsonArray ja, String defaultValue, int FLAGS)
032            .strArr(enumArr, null, 0)
033            .sorted(String::compareTo)
034            .collect(ReadOnlyArrayList.streamCollector());
035
036        // All elements in "enum" must be **NON-NULL**
037        for (int i = 0; i < enumVals.size(); i++)
038
039            if (enumVals.get(i) == null) THIS.verifyThrow(
040                "'enum'[" + i + "] must be a non null JSON string\n" +
041                "'enum': " + enumVals.toString()
042            );
043
044
045        // Inside THIS Super-Class (Entity), the top-level 'type' Property WILL ONLY BE ANALYZED if
046        // there is a JsonArray present which has name "enum".  The extraction of "type" is only
047        // used for assertion-checks / error-checks
048        // 
049        // When "enum" exists, a "type" property must also exist within 'jo'.
050        // Furthermore, rhe *ONLY* legitimate value it may have is the String-Literal "string"
051        // 
052        // Say that 3 times fast: A "JSON String Literal" whose only permitted value is the ASCII
053        // sequence: "string"
054        // 
055        // ReadJSON Method:
056        // getString(JsonObject jo, String propertyName, boolean isOptional, boolean throwOnNull)
057
058        final String typeProp = ReadJSON.getString(jo, "type", false, true);
059
060        if (! typeProp.equals("string")) THIS.verifyThrow(
061            "The Entity being built has an 'enum' property, but its 'type' was not \"string\". " +
062            "type: " + typeProp + "\n" +
063            "'enum': " + enumVals.toString()
064        );
065
066        return enumVals;
067    }
068}