1   /*
2    * SPDX-FileCopyrightText: none
3    * SPDX-License-Identifier: CC0-1.0
4    */
5   
6   package dev.metaschema.core.metapath.item.atomic;
7   
8   import dev.metaschema.core.datatype.markup.IMarkupString;
9   import dev.metaschema.core.datatype.markup.MarkupDataTypeProvider;
10  import dev.metaschema.core.metapath.function.InvalidValueForCastFunctionException;
11  import dev.metaschema.core.metapath.type.IAtomicOrUnionType;
12  import dev.metaschema.core.metapath.type.InvalidTypeMetapathException;
13  import edu.umd.cs.findbugs.annotations.NonNull;
14  
15  /**
16   * An atomic Metapath item representing a Markup data value.
17   */
18  public interface IMarkupItem extends IAnyAtomicItem {
19    /**
20     * Get the type information for this item.
21     *
22     * @return the type information
23     */
24    @NonNull
25    static IAtomicOrUnionType<IMarkupItem> type() {
26      return MarkupDataTypeProvider.MARKUP_TYPE;
27    }
28  
29    @Override
30    default IAtomicOrUnionType<? extends IMarkupItem> getType() {
31      return type();
32    }
33  
34    /**
35     * Cast the provided type to this item type.
36     *
37     * @param item
38     *          the item to cast
39     * @return the original item if it is already this type, otherwise a new item
40     *         cast to this type
41     * @throws InvalidValueForCastFunctionException
42     *           if the provided {@code item} cannot be cast to this type
43     */
44    @NonNull
45    static IMarkupItem cast(@NonNull IAnyAtomicItem item) {
46      try {
47        return item instanceof IMarkupItem
48            ? (IMarkupItem) item
49            : IMarkupMultilineItem.valueOf(item.asString());
50      } catch (IllegalStateException | InvalidTypeMetapathException ex) {
51        // asString can throw IllegalStateException exception
52        throw new InvalidValueForCastFunctionException(ex);
53      }
54    }
55  
56    /**
57     * Get the "wrapped" markup value.
58     *
59     * @return the underlying markup value
60     */
61    @NonNull
62    IMarkupString<?> asMarkup();
63  
64    @Override
65    default IMarkupItem castAsType(IAnyAtomicItem item) {
66      return cast(item);
67    }
68  
69    /**
70     * Compares this value with the argument.
71     *
72     * @param item
73     *          the item to compare with this value
74     * @return a negative integer, zero, or a positive integer if this value is less
75     *         than, equal to, or greater than the {@code item}.
76     */
77    default int compareTo(@NonNull IMarkupItem item) {
78      return asString().compareTo(item.asString());
79    }
80  }