/*
 * 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.util;

import com.fasterxml.jackson.core.JsonProcessingException;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public final class ReportUtil {
    private ReportUtil() {
    }

    public static void writeReportToStdout(Report report) {
        report.writeReport(ReportHelper.STDOUT);
    }

    public static void appendAtomically(Path fileName, byte[] content) {
        appendAtomically(fileName.toFile(), content);
    }

    public static void appendAtomically(File file, byte[] content) {
        try (FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
             FileLock lock = lockIfPossible(channel)) {
            channel.position(channel.size());
            channel.write(ByteBuffer.wrap(content));
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    }

    public static void writeAtomically(Path fileName, byte[] content) {
        writeAtomically(fileName.toFile(), content);
    }

    public static void writeAtomically(File file, byte[] content) {
        try (FileChannel channel = FileChannel.open(file.toPath(),
                StandardOpenOption.WRITE, StandardOpenOption.CREATE);
             FileLock lock = lockIfPossible(channel)) {
            channel.truncate(0);
            channel.write(ByteBuffer.wrap(content));
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    }

    static FileLock lockIfPossible(FileChannel channel) {
        try {
            return channel.lock();
        } catch (Exception e) {
            return null;
        }
    }

    static byte[] humanReadableReportContents(Report report, boolean endMarker) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ReportHelper helper = new ReportHelper(bos, false);
        report.writeReport(helper);
        if (endMarker)
            helper.end();
        return bos.toByteArray();
    }

    static byte[] jsonReportContents(Report report, boolean jsonl) {
        try {
            String content = jsonl
                    ? GlobalObjectMappers.toOneLine(report) + "\n"
                    : GlobalObjectMappers.getPretty().writeValueAsString(report);
            return content.getBytes(StandardCharsets.UTF_8);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static void appendReport(Path reportFileName, Report report) {
        appendAtomically(reportFileName, humanReadableReportContents(report, true));
    }

    public static void appendJsonReport(Path reportFileName, Report report) {
        appendAtomically(reportFileName, jsonReportContents(report, true));
    }

    public static void writeReport(Path reportFileName, Report report) {
        writeAtomically(reportFileName, humanReadableReportContents(report, false));
    }

    public static void writeJsonReport(Path reportFileName, Report report) {
        writeAtomically(reportFileName, jsonReportContents(report, false));
    }
}
