#!/usr/bin/env python
import xml.etree.ElementTree as ET
import os
import re
import codecs

from px4params import scope, cmakeparser

if len(os.sys.argv) < 2:
    print("Error in %s" % os.sys.argv[0])
    print("Usage: %s <parameters.xml> [cmake-file-scoping] " % os.sys.argv[0])
    raise SystemExit

cmake_scope = scope.Scope()
if len(os.sys.argv) == 3:
	with codecs.open(os.sys.argv[2], 'r', 'utf-8') as f:
		try:
			contents = f.read()
			f.close()
			parser = cmakeparser.CMakeParser()
			parser.Parse(cmake_scope, contents)
		except:
			contents = ''
			print('Failed reading file: %s, skipping scoping.' % os.sys.argv[2])
			pass

fp_header = open("px4_parameters.h", "w")
fp_src = open("px4_parameters.c", "w")

tree = ET.parse(os.sys.argv[1])
root = tree.getroot()

# Generate the header file content
header = """
#include <stdint.h>
#include <systemlib/param/param.h>

// DO NOT EDIT
// This file is autogenerated from parameters.xml

__BEGIN_DECLS

struct px4_parameters_t {
"""
params = []
for group in root:
	if group.tag == "group" and "no_code_generation" not in group.attrib:
		for param in group:
			scope_ = param.find('scope').text
			if not cmake_scope.Has(scope_):
				continue
			params.append(param)

params = sorted(params, key=lambda name: name.attrib["name"])
for param in params:
	header += """
	const struct param_info_s __param__%s;""" % param.attrib["name"]

header += """
	const unsigned int param_count;
};

extern const struct px4_parameters_t px4_parameters;
"""

# Generate the C file content
src = """
#include <px4_parameters.h>

// DO NOT EDIT
// This file is autogenerated from paramaters.xml

const
#ifndef __PX4_DARWIN
__attribute__((used, section("__param")))
#endif
struct px4_parameters_t px4_parameters = {
"""
i=0
for param in params:
	val_str = "#error UNKNOWN PARAM TYPE, FIX px_generate_params.py"
	if (param.attrib["type"] == "FLOAT"):
		val_str = ".val.f = "
	elif (param.attrib["type"] == "INT32"):
		val_str = ".val.i = "
	i+=1
	src += """
	{
		"%s",
		PARAM_TYPE_%s,
		%s%s
	},
""" % (param.attrib["name"], param.attrib["type"], val_str, param.attrib["default"])
src += """
	%d
};

//extern const struct px4_parameters_t px4_parameters;

__END_DECLS

""" % i

fp_header.write(header)
fp_src.write(src)
fp_header.close()
fp_src.close()
