#!/usr/bin/env ruby

require 'fileutils'
require 'yaml'

yaml = YAML.load_file('./Specs/LKAlphaComSpecs.yml')

build_dir = "./build"
unless File.directory?(build_dir)
  FileUtils.mkdir_p(build_dir)
end

com_specs = ""
com_specs_file_name = "LKAlphaComSpecs.h"
com_specs_file = "./Sources/#{com_specs_file_name}"

format_command = "astyle --style=stroustrup --indent-namespaces #{com_specs_file}"
compile_command = "g++ --std=c++2a -Wno-deprecated #{com_specs_file}"

def parse_yaml(yaml_data, output_file)

	for k in yaml_data.keys

		if !yaml_data[k].is_a?(Hash)

			if yaml_data[k].is_a?(Array)
				output_file << "\tframe_t #{k}[] = {#{yaml_data[k].map{ |v| sprintf("0x%02X",v)  }.join(", ")}};\n"
			elsif k == "LEKA_ALPHA_COM_SPECS"
				output_file << "\tconst char #{k}[] = \"#{yaml_data[k]}\";\n"
			elsif yaml_data[k].is_a?(String)
				output_file << "\tconst frame_t #{k} = #{yaml_data[k]};\n"
			else
				output_file << "\tconst frame_t #{k} = #{sprintf("0x%02X", yaml_data[k])};\n"
			end

		else

			output_file << "\nnamespace #{k} {\n\n"
			parse_yaml(yaml_data[k], output_file)
			output_file << "\n}\n"

		end

	end
end


com_specs << """
//
//  #{com_specs_file_name}
//
//  Generated by Ladislas de Toldi on #{Time.now.strftime("%Y/%m/%d") }.
//  Copyright © 2018 Leka Inc. All rights reserved.
//

#ifndef _LEKA_ALPHA_COM_SPECS_H_
#define _LEKA_ALPHA_COM_SPECS_H_

#include <stdint.h>

using frame_t = uint8_t;\n\n
"""

parse_yaml(yaml, com_specs)

com_specs << """
#endif

"""

File.open("#{com_specs_file}", "w") {|f| f.write(com_specs) }

puts
cmd_format = system(format_command)
cmd_compile = system(compile_command)

File.delete("#{com_specs_file}.gch")
File.delete("#{com_specs_file}.orig")

file_output = File.read(com_specs_file);
puts file_output;

