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.datatype;
019
020import com.google.common.collect.ImmutableSortedMap;
021
022import dev.enola.data.RepositoryBuilder;
023
024import java.util.Optional;
025
026public class DatatypeRepositoryBuilder extends RepositoryBuilder<Datatype<?>> {
027
028    @Override
029    protected String getIRI(Datatype<?> datatype) {
030        return require(datatype.iri(), "iri");
031    }
032
033    @Override
034    public DatatypeRepositoryBuilder store(Datatype<?> item) {
035        super.store(item);
036        return this;
037    }
038
039    @Override
040    public DatatypeRepositoryBuilder storeAll(Iterable<Datatype<?>> items) {
041        super.storeAll(items);
042        return this;
043    }
044
045    @Override
046    public DatatypeRepository build() {
047        return new ImmutableDatatypeRepository(buildMap());
048    }
049
050    private static class ImmutableDatatypeRepository
051            extends RepositoryBuilder.RepositoryImpl<Datatype<?>> implements DatatypeRepository {
052
053        protected ImmutableDatatypeRepository(ImmutableSortedMap<String, Datatype<?>> items) {
054            super(items);
055        }
056
057        @Override
058        public Optional<Datatype<?>> match(String text) {
059            for (var datatype : list()) {
060                var pattern = datatype.pattern();
061                if (pattern.isEmpty()) continue;
062                if (pattern.get().matcher(text).matches()) return Optional.of(datatype);
063            }
064            return Optional.empty();
065        }
066    }
067}