/*
 * Copyright (c) 2022 MiLaboratories Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.milaboratory.primitivio;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Objects;
import java.util.function.Function;

public final class JSONSerializer implements Serializer {
    final ObjectMapper objectMapper;
    final Class<?> type;
    final Function<byte[], byte[]> preprocessor;

    /**
     * Constructor for backward-compatibility mocking serializers
     *
     * @param objectMapper object mapper to use during serialization and deserialization
     * @param type         target type
     * @param preprocessor JSON string content preprocessor
     */
    public JSONSerializer(ObjectMapper objectMapper, Class<?> type, Function<byte[], byte[]> preprocessor) {
        this.objectMapper = Objects.requireNonNull(objectMapper);
        this.type = Objects.requireNonNull(type);
        this.preprocessor = preprocessor;
    }

    /**
     * Normal constructor, not intended for direct use,
     * use {@link com.milaboratory.primitivio.annotations.Serializable#asJson()} instead.
     *
     * @param objectMapper object mapper to use during serialization and deserialization
     * @param type         target type
     */
    public JSONSerializer(ObjectMapper objectMapper, Class<?> type) {
        this(objectMapper, type, null);
    }

    @Override
    public void write(PrimitivO output, Object object) {
        try {
            if (preprocessor != null)
                throw new IllegalStateException("");
            byte[] bytes = objectMapper.writeValueAsBytes(object);
            output.writeObject(bytes);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Object read(PrimitivI input) {
        byte[] bytes = input.readObject(byte[].class);
        try {
            return objectMapper.readValue(
                    preprocessor != null
                            ? preprocessor.apply(bytes)
                            : bytes,
                    type);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean isReference() {
        return true;
    }

    @Override
    public boolean handlesReference() {
        return false;
    }
}
