package org.example;


import com.example.book.Book;
import com.google.protobuf.InvalidProtocolBufferException;
import java.util.Arrays;
import java.nio.charset.StandardCharsets;



public class Main {

    public static void main(String[] args) {



        // Nested Message
        Book.Publisher publisher = Book.Publisher.newBuilder()
                .setName("O'Reilly")
                .setLocation("USA")
                .build();

        // Book
        Book myBook = Book.newBuilder()
                .setTitle("gRPC")
                .setAuthor("Rawan")
                .setIsbn("123 456 789")
                .setPublicationYear(2025)
                .setGenre(Book.Genre.SCIENCE)
                .setPublisher(publisher)
                .build();

        System.out.println(" before encoding ");
        System.out.println(myBook);


        // Serialization

        byte[] bookAsBytes = myBook.toByteArray();

        System.out.println("\n Encode ");
        System.out.println("Coded to " + bookAsBytes.length + " bytes");
        System.out.println(" "+ Arrays.toString(bookAsBytes));


        // Deserialization

        try {

            Book decodedBook = Book.parseFrom(bookAsBytes);

            System.out.println("\n after decode");
            System.out.println(decodedBook);


            System.out.println("\n Data verification ");
            System.out.println(" " + myBook.equals(decodedBook));
            System.out.println("Is the original object equal to the decoded object : " + decodedBook.getPublisher().getName());

        } catch (InvalidProtocolBufferException e) {
            System.err.println("An error occurred while decoding : " + e.getMessage());
        }
        // Comparison with JSON

        String bookAsJson = """
        {
          "title": "gRPC: The Definitive Guide",
          "author": "Rawan",
          "isbn": "123-456-789",
          "publication_year": 2025,
          "genre": "SCIENCE",
          "publisher": {
            "name": "O'Reilly",
            "location": "USA"
          }
        }
        """;

        int jsonSize = bookAsJson.getBytes(StandardCharsets.UTF_8).length;
        int protoSize = bookAsBytes.length;

        System.out.println("\n Protobuf size comparison with JSON ");
        System.out.println(" Protobuf: " + protoSize + " bytes");
        System.out.println(" JSON:     " + jsonSize + "  bytes");


    }
}