/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 org.apache.dubbo.common.serialize.jackson;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.apache.dubbo.common.serialize.DefaultJsonDataOutput;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;

/**
 * Jackson object output implementation
 */
public class JacksonObjectOutput implements DefaultJsonDataOutput {

    private final ObjectMapper MAPPER;

    private final PrintWriter WRITER;

    public JacksonObjectOutput(OutputStream outputStream) {
        this(new OutputStreamWriter(outputStream));
    }

    public JacksonObjectOutput(Writer writer) {
        this.WRITER = new PrintWriter(writer);
        this.MAPPER = new ObjectMapper()
            .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .registerModule(new JavaTimeModule())
        ;
    }

    @Override
    public void writeObject(Object obj) throws IOException {
        char[] jsonChars = convertJsonToCharArray(MAPPER.writeValueAsString(obj));
        WRITER.write(jsonChars, 0, jsonChars.length);
        WRITER.println();
        WRITER.flush();
    }

    @Override
    public void writeBytes(byte[] v) throws IOException {
        WRITER.println(new String(v));
    }

    @Override
    public void writeBytes(byte[] v, int off, int len) throws IOException {
        WRITER.println(new String(v, off, len));
    }

    @Override
    public void flushBuffer() throws IOException {
        WRITER.flush();
    }

    private char[] convertJsonToCharArray(String json) {
        return json.toCharArray();
    }

}
