# Copyright (c) 2015, InfluxFramework LLC
# License: MIT. See LICENSE

import json

import influxframework
from influxframework.model.document import Document
from influxframework.translate import get_translator_url
from influxframework.utils import is_html, strip_html_tags


class Translation(Document):
	def validate(self):
		if is_html(self.source_text):
			self.remove_html_from_source()

	def remove_html_from_source(self):
		self.source_text = strip_html_tags(self.source_text).strip()

	def on_update(self):
		clear_user_translation_cache(self.language)

	def on_trash(self):
		clear_user_translation_cache(self.language)

	def contribute(self):
		pass

	def get_contribution_status(self):
		pass


@influxframework.whitelist()
def create_translations(translation_map, language):
	from influxframework.influxframeworkclient import InfluxFrameworkClient

	translation_map = json.loads(translation_map)
	translation_map_to_send = influxframework._dict({})
	# first create / update local user translations
	for source_id, translation_dict in translation_map.items():
		translation_dict = influxframework._dict(translation_dict)
		existing_doc_name = influxframework.get_all(
			"Translation",
			{
				"source_text": translation_dict.source_text,
				"context": translation_dict.context or "",
				"language": language,
			},
		)
		translation_map_to_send[source_id] = translation_dict
		if existing_doc_name:
			influxframework.db.set_value(
				"Translation",
				existing_doc_name[0].name,
				{
					"translated_text": translation_dict.translated_text,
					"contributed": 1,
					"contribution_status": "Pending",
				},
			)
			translation_map_to_send[source_id].name = existing_doc_name[0].name
		else:
			doc = influxframework.get_doc(
				{
					"doctype": "Translation",
					"source_text": translation_dict.source_text,
					"contributed": 1,
					"contribution_status": "Pending",
					"translated_text": translation_dict.translated_text,
					"context": translation_dict.context,
					"language": language,
				}
			)
			doc.insert()
			translation_map_to_send[source_id].name = doc.name

	params = {
		"language": language,
		"contributor_email": influxframework.session.user,
		"contributor_name": influxframework.utils.get_fullname(influxframework.session.user),
		"translation_map": json.dumps(translation_map_to_send),
	}

	translator = InfluxFrameworkClient(get_translator_url())
	added_translations = translator.post_api("translator.api.add_translations", params=params)

	for local_docname, remote_docname in added_translations.items():
		influxframework.db.set_value("Translation", local_docname, "contribution_docname", remote_docname)


def clear_user_translation_cache(lang):
	influxframework.cache().hdel("lang_user_translations", lang)
