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.common.convert;
019
020import java.io.IOException;
021import java.text.FieldPosition;
022import java.text.Format;
023import java.text.ParseException;
024
025public class ObjectToStringBiConverterWithFormat implements ObjectToStringBiConverter<Object> {
026
027    @SuppressWarnings("Immutable")
028    private final Format format;
029
030    public ObjectToStringBiConverterWithFormat(Format format) {
031        this.format = format;
032    }
033
034    @Override
035    public String convertTo(Object input) {
036        return format.format(input);
037    }
038
039    @Override
040    public Object convertFrom(String input) throws IllegalArgumentException {
041        try {
042            return format.parseObject(input);
043        } catch (ParseException e) {
044            throw new IllegalArgumentException("Failed to convert: " + input, e);
045        }
046    }
047
048    @Override
049    public boolean convertInto(Object from, Appendable into) throws ConversionException {
050        // TODO Test if this really works like this...
051        // TODO How to use StringBuilder instead of StringBuffer with java.text.Format ?!
052        var sb = new StringBuffer();
053        format.format(from, sb, ALL_FIELD_POSITIONS);
054        try {
055            into.append(sb);
056        } catch (IOException e) {
057            throw new ConversionException("append() failed: " + sb, e);
058        }
059        return true;
060    }
061
062    private static final FieldPosition ALL_FIELD_POSITIONS = new FieldPosition(-1);
063}