#!/usr/bin/env python3
# -*- coding: UTF_8 -*-

import sys
import warnings
import json
import os

#Le script d'import quand à lui renvoie un Warning lorsque aucun paramètre ne correspond .
#Ce Warning contient le fichier importé concerné et préviens de la valeur qui n'a pas été acceptée.

def warning_style(message, category, filename, lineno, file=None, line=None):
	return ' %s:%s: %s: %s\n' % (filename, lineno, category.__name__, message)


warnings.formatwarning = warning_style

def clean_type(measure_type_string):
	"""
	This function allows us to clean the data type that we want to search.

	Only by lowering the input, and replacing every '-' by '_'.

	Parameters
	----------
	measure_type_string: str
		The input, what we want to clean.

	Returns
	-------
	res: str
		What we just cleaned.
	"""
	lower = measure_type_string.lower()
	res = lower.replace("-", "_")

	# remove all white spaces and beginning or end of the string
	tocheck = 1
	while tocheck:
		if res[0]!=" " and res[-1]!=" ":
			tocheck=0
		elif res[0]==" ":
			res = res[1:]
		elif res[-1]==" ":
			res = res[:-1]

	# replace white spaces in the middle of the string by underscores
	return res.replace(" ","_")

def translate_key(raw_key, _type="data"):
	"""
	Translate data_types through a translation json file. Returns None if raw_key not in json file.

	Parameters
	----------
	raw_key: string

	Returns
	-------
	translated_key: string or None
	"""

	translated_key = None

	# use of a json file for the translation in valid data type names for the DB
	# _transation_path = os.path.dirname(os.path.realpath(__file__))+'/translation.json'
	#
	# print(f"os.path.realpath(__file__) : {os.path.realpath(__file__)}")

	# cwd = os.getcwd()
	# print(f"cwd : {cwd}")
	# # print(f"os.path.dirname(os.path.abspath(__file__)) : {os.path.dirname(os.path.abspath(__file__))}")
	# # _transation_path = os.path.abspath(__file__).split('convert_type.py')[0] + "translation.json"
	# _transation_path = cwd + "/Model/udt_extract/translation.json"
	# # print("path : ", os.path.dirname(os.path.abspath(sys.argv[0])))
	# print(f"_transation_path : {_transation_path}")
	# print(f"__file__ : {__file__}")

	# f = open(_transation_path)

	# f = open(".translation.json", "r")
	# translation_dict = json.loads(f.read())[_type]

	# for key, value in translation_dict.items():
	# 	# leave unchanged the already valid data type names
	# 	# translate those which are translatable
	# 	# print(f"key : {key}, value : {value}")
	# 	if (raw_key == key):
	# 		translated_key = key
	# 		break
	# 	elif value["alter_ego"] is not None:
	# 		if raw_key in value["alter_ego"]:
	# 			translated_key = key
	# 			break

	translation_dict = {"data" : { "echo_avg_profile": {"alter_ego":["amplitude"], "unit": "V", "graph_title": "Echo"},
								   "velocity_avg_profile": {"alter_ego":["velocity"], "unit": "m/s", "graph_title": "Velocity"},
								   "snr_doppler_avg_profile": {"alter_ego":["snr"], "unit": "dB", "graph_title": "SNR <br> Doppler"},
								   "velocity_std_profile": {"alter_ego":["std_velocity", "std"], "unit": "m/s", "graph_title": "Velocity <br> standard deviation"},
								   "turbidity_avg_profile": {"alter_ego":["turbi"], "unit": "1/m" },
								   "saturation_avg_profile": {"alter_ego":["saturation"], "unit": None},
								   "ny_jump_avg_profile": {"alter_ego":None, "unit": None},
								   "saturation_profile": {"alter_ego":None, "unit": None},
								   "ny_jump_profile": {"alter_ego":None, "unit": None},
								   "echo_profile": {"alter_ego":["instamplitude"], "unit": "V", "graph_title": "Echo"},
								   "velocity_profile": {"alter_ego":["instvelocity"], "unit": "m/s", "graph_title": "Velocity"},
								   "snr_doppler_profile": {"alter_ego":["instsnr"], "unit": "dB", "graph_title": "SNR <br> Doppler"},
								   "turbidity_profile": {"alter_ego":["instturbi"], "unit": "1/m"},
								   "temperature": {"alter_ego":["temp"], "unit": "K"},
								   "sound_speed": {"alter_ego": None, "unit": "m/s"},
								   "roll": {"alter_ego": None, "unit": "rad"},
								   "pitch": {"alter_ego": None, "unit": "rad"},
								   "velocity_avg": {"alter_ego": ["v_moy"], "unit": "m/s"},
								   "velocity_max": {"alter_ego": ["v_max"], "unit": "m/s"},
								   "velocity_min": {"alter_ego": ["v_min"], "unit": "m/s"},
								   "velocity_std": {"alter_ego": ["v_std"], "unit": "m/s"},
								   "snr_doppler_avg": {"alter_ego": ["snr_doppler"], "unit": "dB"},
								   "snr_echo_avg": {"alter_ego": ["snr_echo"], "unit": "dB"},
								   "rate_doppler": {"alter_ego": ["n_good"], "unit": "%"},
								   "velocity_distribution": {"alter_ego": ["tests_av_distrib_in_air","tests_av_distrib_in_flume", "distrib"], "unit": None},
								   "noise_g_high": {"alter_ego": ["noise"], "unit": "V"},
								   "noise_g_low": {"alter_ego": None, "unit": "V"}
								  },
						"param_const" : {"operator" : {"alter_ego": None, "unit": None},
										 "comments" : {"alter_ego": None, "unit": None},
										 "emitter" : {"alter_ego": ["tr_out"], "unit": None},
										 "receiver" : {"alter_ego": ["tr_in"], "unit": None}
													},
						"param_var" : {"f0": {"alter_ego": None, "unit": "Hz"},
									   "v_min": {"alter_ego": ["v_min_1"], "unit": "m/s"},
									   "v_max": {"alter_ego": None, "unit": "m/s"},
									   "prf": {"alter_ego": None, "unit": "Hz"},
									   "r_cell1": {"alter_ego": ["r_vol1"], "unit": "m"},
									   "r_dcell": {"alter_ego": ["r_dvol"], "unit": "m"},
									   "n_cell": {"alter_ego": ["n_vol"], "unit": None},
									   "r_em": {"alter_ego": None, "unit": "m"},
									   "n_p": {"alter_ego": ["n_ech"], "unit": None},
									   "v_em": {"alter_ego": None, "unit": "V"},
									   "n_avg": {"alter_ego": ["n_profile", "n_profil"], "unit": None},
									   "a0": {"alter_ego": ["gain_a0"], "unit": "dB"},
									   "a1": {"alter_ego": ["gain_a1"], "unit": "dB/m"},
									   "phase_coding": {"alter_ego": None, "unit": None},
									   "static_echo_filter": {"alter_ego": None, "unit": None},
									   "sound_speed": {"alter_ego": None, "unit": "m/s"}
									}
						}

	for key_dict, values_dict in translation_dict.items():
		for key, value in values_dict.items():
			# leave unchanged the already valid data type names
			# translate those which are translatable
			# print(f"key : {key}, value : {value}")
			if (raw_key == key):
				translated_key = key
				break
			elif value["alter_ego"] is not None:
				if raw_key in value["alter_ego"]:
					translated_key = key
					break

	#if translated_key == None:
	#	print("delete %s"%raw_key)

	# print(f"translated_key : {translated_key}")
	return translated_key

def translate_paramdict(param_dict):
	"""
	Parse a dict and translate param_names and clean out those not to be imported in the ORM

	Parameters
	----------
	param_dicts: dict

	Returns
	-------
	param_dict: dict
	"""
	translated_param_dict = {}
	for key,elem in param_dict.items():
		if translate_key(clean_type(key),_type="param_var") is not None:
			translated_param_dict[translate_key(clean_type(key),_type="param_var")] = elem
		elif translate_key(clean_type(key),_type="param_const") is not None:
			translated_param_dict[translate_key(clean_type(key), _type="param_const")] = elem
	return translated_param_dict

def translate_datadictslist(data_dicts):
	"""
	Parse a list of dicts and translate data_types and clean out those not to be imported in the ORM
	Can be used on scalar or vector dicts.

	Parameters
	----------
	data_dicts: list(dict)

	Returns
	-------
	importable_data_dicts: list(dict)
	"""
	importable_data_dicts = []
	i=0
	for data_dict in data_dicts:
		importable_data_dicts.append(data_dict)
		# standardisation of the data type names --> only underscores and lower case
		importable_data_dicts[i]['name'] = clean_type(data_dict['name'])

		# traduire les noms qui ont une traduction (cf switcher dans convert_type.py)
		importable_data_dicts[i]['name'] = translate_key(importable_data_dicts[i]['name'], _type="data")
		if importable_data_dicts[i]['name'] is None:
		# supprimer les lignes sont le type n'existe pas la la liste de données importables
			del importable_data_dicts[i]
		else:
			i=i+1

	return importable_data_dicts
