#!/usr/bin/env ruby
# frozen_string_literal: true

require_relative 'log_pb'
require 'google/protobuf/well_known_types' # Google::Protobuf::Timestamp
require 'optparse'
require 'json'

def get_serialized_log
  log = Service::Logging::Log.new
  log.context = Service::Logging::Log::Context.new(
    timestamp: Google::Protobuf::Timestamp.new(seconds: Time.now.to_i, nanos: 0),
    host_or_ip: '192.168.xxx.xxx',
    service_name: 'test',
    user: 'test'
  )
  log.level = Service::Logging::Log::Level::INFO
  log.message = "This is a test log generated by [#{$PROGRAM_NAME}]."

  Service::Logging::Log.encode(log)
end

def get_deserialized_log(serialized_log)
  Service::Logging::Log.decode(serialized_log)
end

OptionParser.new do |parser|
  parser.banner = "Usage: #{$PROGRAM_NAME} [option] FILENAME"

  parser.on('-w', '--write FILENAME', 'write protobuf (binary) log') do |filename|
    print "Writing protobuf sample log file [#{filename}]... "
    File.open(filename, 'wb') do |file|
      file.write(get_serialized_log)
    end
    puts '[DONE]'
  end

  parser.on('-r', '--read FILENAME', 'read protobuf (binary) log') do |filename|
    puts "Dumping protobuf binary file [#{filename}]..."
    File.open(filename, 'rb') do |file|
      deserialized_log = get_deserialized_log(file.read)
      puts deserialized_log.inspect
    end
    puts '[DONE]'
  end

  parser.on('-j', '--read-json FILENAME', 'read protobuf (binary) log as JSON') do |filename|
    puts "Dumping protobuf binary file as JSON [#{filename}]..."
    File.open(filename, 'rb') do |file|
      deserialized_log = get_deserialized_log(file.read)
      json_log = Service::Logging::Log.encode_json(deserialized_log)
      puts JSON.pretty_generate(JSON[json_log])
    end
    puts '[DONE]'
  end
end.parse!
