001/*
002 * SPDX-License-Identifier: Apache-2.0
003 *
004 * Copyright 2024-2026 The Enola <https://enola.dev> Authors
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 *     https://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package dev.enola.thing;
019
020import com.google.common.reflect.TypeToken;
021import com.google.errorprone.annotations.CanIgnoreReturnValue;
022import com.google.errorprone.annotations.ImmutableTypeParameter;
023
024import dev.enola.common.convert.ConversionException;
025import dev.enola.thing.repo.ThingProvider;
026
027import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
028
029import org.jspecify.annotations.Nullable;
030
031import java.net.URI;
032import java.util.*;
033
034/**
035 * PredicatesObjects is a "struct" of Predicates and their Objects.
036 *
037 * <p>Contrary to a {@link Thing}, this has no "identity" and thus no IRI. RDF calls this a "Blank
038 * Node". This is informally often also referred to as a Things's Properties - it's just the Thing
039 * without its identifying IRI.
040 *
041 * <p>It is typically used for objects "contained inside" Things (or their nested sub-structs).
042 */
043public interface PredicatesObjects /*<TT /*extends PredicatesObjects<?>>*/ {
044
045    // TODO Write default implementation of as() with ProxyTBF...
046    // default <U extends PredicatesObjects<TT>> U as(Class<U> clazz) {
047
048    /**
049     * The Map's key is the IRI of a predicate, and the value is as would be returned by {@link
050     * #get(String)}.
051     */
052    @Deprecated // TODO Re-think API... I would like to avoid exposing Object - remove this?
053    Map<String, Object> properties();
054
055    /** IRIs of the Predicates of this Thing. */
056    // TODO Reconsider if this method is really required? Why not just #properties().keySet()?
057    // ^^^ it's useful to avoid loading a huge Thing entirely into memory...
058    // TODO Use Iterable<> instead Set<>
059    Set<String> predicateIRIs();
060
061    // TODO These is*() methods could be replaced with a Visitor - but how-to for nested Structs?!
062    // Look into e.g. how EMF does Visitors...
063
064    // boolean isLink(String predicateIRI) is intentionally not available; use #getLinks() instead!
065
066    default boolean isLinkObject(@Nullable Object object) {
067        // TODO object instanceof HasIRI, instead of Link ?
068        return object instanceof URI || object instanceof Link;
069    }
070
071    default boolean isIterable(String predicateIRI) {
072        var value = get(predicateIRI);
073        return value instanceof Iterable;
074    }
075
076    default boolean isOrdered(String predicateIRI) {
077        var value = get(predicateIRI);
078        return value instanceof List;
079    }
080
081    default boolean isStruct(String predicateIRI) {
082        var value = get(predicateIRI);
083        return value instanceof PredicatesObjects;
084    }
085
086    // TODO isLangString(String predicateIRI) needed? How would it be used?
087
088    // NB: isLiteral(String predicateIRI) is not needed; Datatype conversion handles that.
089
090    /**
091     * IRI of datatype of predicate, if any (else null). Not all predicates will have a datatype
092     * set. This is required because the predicate's Object Java class is not necessarily unique;
093     * e.g. both dev.enola.model.schema.Datatypes.DATE as well as dev.enola.model.xsd.DATE are
094     * java.time.LocalDate instances.
095     */
096    @Nullable String datatype(String predicateIRI);
097
098    default @Nullable String datatype(HasPredicateIRI predicateIRI) {
099        return datatype(predicateIRI.iri());
100    }
101
102    @Deprecated // TODO Is this really useful? In which use case scenario? Remove...
103    Map<String, String> datatypes();
104
105    /**
106     * Object of predicate. The type is e.g. directly a String, Integer etc. Alternatively, it may
107     * be a {@link Link} (or {@link URI}) with an IRI or another PredicatesObjects (for an "inline
108     * embedded/expanded blank node") or a {@link java.util.List} of such items. The object is
109     * immutable. May be null if Thing has no such predicate.
110     *
111     * @deprecated Use {@link #get(String, Class)} instead.
112     */
113    @Deprecated // TODO Remove after adopting ThingVisitor
114    //  Note bene: Cannot always just replace all usages with #get(String, aClass | Object.class);
115    //    actually technically with Object.class we could; but the ThingVisitor is better!
116    <T> @Nullable T get(String predicateIRI);
117
118    /**
119     * Object of predicate, with type conversion - or failure.
120     *
121     * <p>BEWARE: This may well fail and throw an <code>IllegalArgumentException</code>! You can
122     * never really be sure what Java type an object of a predicate is. If in doubt, use {@link
123     * #getOptional(String, Class)}, or perhaps {@link #get(String)} with an {@link
124     * dev.enola.common.convert.ObjectClassConverter}.
125     */
126    @Deprecated // TODO Remove; create & replace callers with #get(String, Class, Class)
127    default <T> @Nullable T get(String predicateIRI, Class<T> klass) {
128        return getOptional(predicateIRI, klass).orElse(null);
129    }
130
131    @Deprecated // TODO Remove; create & replace callers with #get(HasPredicateIRI, Class, Class)
132    default <T> @Nullable T get(HasPredicateIRI predicate, Class<T> klass) {
133        return get(predicate.iri(), klass);
134    }
135
136    @SuppressWarnings("unchecked")
137    default <T> @Nullable T get(String predicateIRI, TypeToken<T> typeToken) {
138        return (T) get(predicateIRI, typeToken.getRawType());
139    }
140
141    /**
142     * Object of predicate, with type conversion - as Optional.
143     *
144     * @return property as type, if set
145     * @throws IllegalStateException if Datatype is not found, but needed
146     * @throws ConversionException if known Datatype failed to convert
147     */
148    @SuppressWarnings("unchecked")
149    // TODO Remove; create & replace callers with #getOptional(String, Class, Class)
150    default <T> Optional<T> getOptional(String predicateIRI, Class<T> klass) {
151        Object object = get(predicateIRI);
152        return ObjectConversions.as(object, klass, this, predicateIRI);
153    }
154
155    default @Nullable String getString(String predicateIRI) {
156        return getOptional(predicateIRI, String.class).orElse(null);
157    }
158
159    default @Nullable String getString(HasPredicateIRI predicate) {
160        return getString(predicate.iri());
161    }
162
163    @Deprecated // TODO Replace all callers with new variant, see below
164    default <T extends Thing> Optional<T> getThing(String predicateIRI, Class<T> klass) {
165        return getOptional(predicateIRI, String.class)
166                .map(linkIRI -> ThingProvider.CTX.get(linkIRI, klass));
167    }
168
169    // TODO Rename to getThing
170    @Deprecated // TODO Replace all callers with new variant, see below
171    default <T extends Thing> T getThingOrThrow(String predicateIRI, Class<T> klass) {
172        var opt = getOptional(predicateIRI, String.class);
173        if (!opt.isPresent())
174            throw new IllegalStateException(this + " has no value for " + predicateIRI);
175        var thingIRI = opt.get();
176        T thing = ThingProvider.CTX.get(thingIRI, klass);
177        if (thing == null) throw new IllegalStateException(thingIRI + " not found");
178        return thing;
179    }
180
181    // TODO Rename to getThingOpt; or (better) remove Optional, when fully adopting Always*
182    default <T extends Thing, B extends Thing.Builder<T>> Optional<T> getThing(
183            String predicateIRI, Class<T> klass, Class<B> builderClass) {
184        return getOptional(predicateIRI, String.class)
185                .map(linkIRI -> ThingProvider.CTX.get(linkIRI, klass, builderClass));
186    }
187
188    @SuppressWarnings("unchecked")
189    @Deprecated
190    // TODO Remove after creating and replacing all usages with #getThings(String, Class, Class)
191    default <T extends Thing> Iterable<T> getThings(String predicateIRI, Class<T> klass) {
192        var iris = getOptional(predicateIRI, Iterable.class).orElse(Set.of());
193        return ThingProvider.CTX.get(iris, klass);
194    }
195
196    default <T extends Thing, B extends Thing.Builder<T>> Iterable<T> getThings(
197            String predicateIRI, Class<T> klass, Class<B> builderClass) {
198        var iris = getOptional(predicateIRI, Iterable.class).orElse(Set.of());
199        return ThingProvider.CTX.get(iris, klass, builderClass);
200    }
201
202    default Iterable<Thing> getThings(String predicateIRI) {
203        return getThings(predicateIRI, Thing.class, Thing.Builder.class);
204    }
205
206    // TODO Remove after creating and replacing all with #getThings(HasPredicateIRI, Class, Class)
207    default <T extends Thing> Iterable<T> getThings(HasPredicateIRI predicate, Class<T> klass) {
208        return getThings(predicate.iri(), klass);
209    }
210
211    /**
212     * Links, for predicate.
213     *
214     * <p>This transparently correctly handles if said predicate is not a link, a single link, or an
215     * iterable of which some elements are links.
216     *
217     * @return iterable objects which are links. Never null, but may well be empty. The type of the
218     *     contained elements can vary, and be either {@link String}, {@link URI}, {@link Link};
219     *     it's possible to use {@link Object#toString()} to get the IRI of the link, because {@link
220     *     Link#toString()} is implemented as expected.
221     */
222    // TODO ifStruct(), should it recursive into finding links in nested PredicatesObjects?
223    @SuppressWarnings("unchecked")
224    default Collection<Object> getLinks(String predicateIRI) {
225        if (!isIterable(predicateIRI)) {
226            return getOptional(predicateIRI, Object.class)
227                    .filter(this::isLinkObject)
228                    .map(Set::of)
229                    .orElse(Set.of());
230        } else
231            return get(predicateIRI, Collection.class).stream().filter(this::isLinkObject).toList();
232    }
233
234    default boolean hasLink(String predicateIRI, String linkIRI) {
235        var links = getLinks(predicateIRI);
236        for (var link : links) if (link.toString().equals(linkIRI)) return true;
237        return false;
238    }
239
240    // TODO Collection<> get N for other things than Links
241
242    // TODO get... other types.
243
244    Builder<? extends PredicatesObjects> copy();
245
246    @SuppressFBWarnings("NM_SAME_SIMPLE_NAME_AS_INTERFACE")
247    interface Builder<B extends PredicatesObjects> // skipcq: JAVA-E0169
248            extends dev.enola.common.Builder<B> {
249
250        // TODO Add clear(String predicateIRI) method..
251
252        @CanIgnoreReturnValue
253        @SuppressWarnings("Immutable")
254        default Builder<B> set(String predicateIRI, Link link) {
255            set(predicateIRI, (Object) link); // !
256            return this;
257        }
258
259        @CanIgnoreReturnValue
260        default Builder<B> set(String predicateIRI, HasIRI hasIRI) {
261            set(predicateIRI, new Link(hasIRI.iri())); // !
262            return this;
263        }
264
265        @CanIgnoreReturnValue
266        <@ImmutableTypeParameter T> Builder<B> set(String predicateIRI, T value);
267
268        @CanIgnoreReturnValue
269        <@ImmutableTypeParameter T> Builder<B> set(
270                String predicateIRI, T value, @Nullable String datatypeIRI);
271
272        /**
273         * Adds one of possibly several value objects for the given predicate IRI.
274         *
275         * <p>This is UNORDERED! Insertion order may NOT be preserved. Duplicates are not allowed
276         * and will cause an error (possibly only on {@link #build()}). It is an error if this
277         * property has already been set to anything else than a {@link Set}.
278         */
279        @CanIgnoreReturnValue
280        <@ImmutableTypeParameter T> Builder<B> add(String predicateIRI, T value);
281
282        @CanIgnoreReturnValue
283        <@ImmutableTypeParameter T> Builder<B> addAll(String predicateIRI, Iterable<T> values);
284
285        @CanIgnoreReturnValue
286        <@ImmutableTypeParameter T> Builder<B> add(
287                String predicateIRI, T value, @Nullable String datatypeIRI);
288
289        @CanIgnoreReturnValue
290        <@ImmutableTypeParameter T> Builder<B> addAll(
291                String predicateIRI, Iterable<T> values, @Nullable String datatypeIRI);
292
293        /**
294         * Adds one of possibly several value objects for the given predicate IRI - and preserves
295         * order.
296         *
297         * <p>Nota bene: This is <b>ordered</b> (insertion order <i>is</i> preserved), but not
298         * <b>sorted</b> (elements are in the order in which they were added, not [re-]sorted).
299         *
300         * <p>If this property has previously already been set to something other than a List, then
301         * it gets converted to a list (in a random order), and then values gets added.
302         *
303         * <p>Duplicates ARE allowed.
304         */
305        @CanIgnoreReturnValue
306        <@ImmutableTypeParameter T> Builder<B> addOrdered(String predicateIRI, T value);
307
308        @CanIgnoreReturnValue
309        <@ImmutableTypeParameter T> Builder<B> addOrdered(
310                String predicateIRI, T value, @Nullable String datatypeIRI);
311
312        @CanIgnoreReturnValue
313        <@ImmutableTypeParameter T> Builder<B> addAllOrdered(
314                String predicateIRI, Iterable<T> values);
315
316        @CanIgnoreReturnValue
317        default <@ImmutableTypeParameter T> Builder<B> add(HasPredicateIRI predicate, T value) {
318            return add(predicate.iri(), value);
319        }
320
321        @CanIgnoreReturnValue
322        default <@ImmutableTypeParameter T> Builder<B> addAll(
323                HasPredicateIRI predicate, Iterable<T> value) {
324            return addAll(predicate.iri(), value);
325        }
326
327        @CanIgnoreReturnValue
328        default <@ImmutableTypeParameter T> Builder<B> add(
329                HasPredicateIRI predicate, T value, @Nullable String datatypeIRI) {
330            return add(predicate.iri(), value, datatypeIRI);
331        }
332
333        @CanIgnoreReturnValue
334        default <@ImmutableTypeParameter T> Builder<B> addAll(
335                HasPredicateIRI predicate, Iterable<T> value, @Nullable String datatypeIRI) {
336            return addAll(predicate.iri(), value, datatypeIRI);
337        }
338
339        @CanIgnoreReturnValue
340        default <@ImmutableTypeParameter T> Builder<B> addOrdered(
341                HasPredicateIRI predicate, T value) {
342            return addOrdered(predicate.iri(), value);
343        }
344
345        @CanIgnoreReturnValue
346        default <@ImmutableTypeParameter T> Builder<B> addOrdered(
347                HasPredicateIRI predicate, T value, @Nullable String datatypeIRI) {
348            return addOrdered(predicate.iri(), value, datatypeIRI);
349        }
350
351        @Override
352        B build();
353    }
354}