package com.knecon.fforesight.service.layoutparser.processor.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import com.google.protobuf.Message;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.Struct;
import com.google.protobuf.util.JsonFormat;

import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;

@UtilityClass
public class ProtobufUtil {

    public static String toJson(MessageOrBuilder messageOrBuilder) throws IOException {
        return JsonFormat.printer().print(messageOrBuilder);
    }

    @SuppressWarnings("unchecked")
    public static Message fromJson(String json) throws IOException {
        Message.Builder structBuilder = Struct.newBuilder();
        JsonFormat.parser().ignoringUnknownFields().merge(json, structBuilder);
        return structBuilder.build();
    }


    @SneakyThrows
    public <T extends Message> File serializeToTempFile(T any) {
        var tempFile = File.createTempFile("storage-protobuf", ".data");

        try (var fos = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(tempFile)))) {
            any.writeTo(fos);
            return tempFile;
        }
    }

}