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.io;
019
020import static dev.enola.thing.io.UriIntoThingConverters.ContextKey.INPUT;
021
022import com.google.common.collect.ImmutableList;
023
024import dev.enola.common.context.Context;
025import dev.enola.common.context.TLC;
026import dev.enola.common.convert.ConversionException;
027import dev.enola.common.convert.ConverterInto;
028import dev.enola.thing.repo.ThingRepositoryStore;
029
030import java.io.IOException;
031import java.net.URI;
032
033// TODO Make UriIntoThingConverters actually implement UriIntoThingConverter itself (less confusing)
034public class UriIntoThingConverters implements ConverterInto<URI, ThingRepositoryStore> {
035
036    // TODO Load a resource with different converters multi-threaded, in parallel...
037
038    public enum Flags implements Context.Key<Boolean> {
039        ORIGIN
040    }
041
042    private final ImmutableList<UriIntoThingConverter> converters;
043
044    public UriIntoThingConverters(Iterable<UriIntoThingConverter> converters) {
045        this.converters = ImmutableList.copyOf(converters);
046    }
047
048    public UriIntoThingConverters(UriIntoThingConverter... converters) {
049        this.converters = ImmutableList.copyOf(converters);
050    }
051
052    @Override
053    public boolean convertInto(URI from, ThingRepositoryStore into)
054            throws ConversionException, IOException {
055        try (var ctx = TLC.open()) {
056            ctx.push(INPUT, from);
057            for (var converter : converters) {
058                if (converter.convertInto(from, into)) return true;
059            }
060        }
061        return false;
062    }
063
064    // TODO Actually TLC.get(INPUT) *read* this somewhere... ;-) else remove again later.
065    enum ContextKey implements Context.Key<URI> {
066        INPUT
067    }
068}