/*
 * Copyright 2020 Red Hat
 *
 * 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 io.apicurio.registry.content;

import io.apicurio.registry.utils.IoBufferedInputStream;
import io.apicurio.registry.utils.IoUtil;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author Ales Justin
 */
class StreamContentHandle extends AbstractContentHandle {
    private InputStream stream;

    StreamContentHandle(InputStream stream) {
        this.stream = stream;
    }

    @Override
    public InputStream stream() {
        if (bytes != null) {
            return new ByteArrayInputStream(bytes);
        }
        InputStream is = stream;
        stream = null;
        return new IoBufferedInputStream(is, (bytes, count) -> {
            byte[] copy = new byte[count];
            System.arraycopy(bytes, 0, copy, 0, count);
            this.bytes = copy;
        });
    }

    @Override
    public byte[] bytes() {
        if (bytes == null) {
            InputStream is = stream;
            stream = null;
            bytes = IoUtil.toBytes(is);
        }
        return bytes;
    }

    @Override
    public String content() {
        if (content == null) {
            content = new String(bytes(), StandardCharsets.UTF_8);
        }
        return content;
    }
}
