#! /usr/bin/env python3
# -*- coding: utf-8 -*-

#	Copyright 2013, 2017, Marten de Vries
#
#	This file is part of OpenTeacher.
#
#	OpenTeacher is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#
#	OpenTeacher is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with OpenTeacher.  If not, see <http://www.gnu.org/licenses/>.

import contextlib
import os

class JSInputTypingLogicModule:
	"""This module offers an object that can be used to control the part
	   of a GUI where the user types his/her answer in in a test.

	"""
	def __init__(self, moduleManager, *args, **kwargs):
		super().__init__(*args, **kwargs)
		self._mm = moduleManager

		self.type = "jsInputTypingLogic"
		self.requires = (
			self._mm.mods(type="javaScriptEvaluator"),
		)
		self.uses = (
			self._mm.mods(type="translator"),
			self._mm.mods(type="translationIndexBuilder"),
		)
		self.filesWithTranslations = (
			os.path.abspath("./node_modules/ot-input-typing-logic/index.js"),
		)

	def createController(self, *args, **kwargs):
		return self._js.global_['ot-input-typing-logic'].new(*args, **kwargs)

	def enable(self):
		self._modules = next(iter(self._mm.mods(type="modules")))
		self._js = self._modules.default("active", type="javaScriptEvaluator").loadModule('ot-input-typing-logic')

		try:
			translator = self._modules.default("active", type="translator")
		except IndexError:
			pass
		else:
			translator.languageChanged.handle(self._retranslate)
		self._retranslate()

		with contextlib.suppress(IndexError):
			buildTranslationIndex = self._modules.default("active", type="translationIndexBuilder").buildTranslationIndex
			self.translationIndex = buildTranslationIndex(self._mm.resourcePath("translations"))

		self.active = True

	def _retranslate(self):
		try:
			translator = self._modules.default("active", type="translator")
		except IndexError:
			_, ngettext = str, lambda a, b, n: a if n == 1 else b
		else:
			_, ngettext = translator.gettextFunctions(
				self._mm.resourcePath("translations")
			)
		self._js.global_._ = _
		self._js.global_.ngettext = ngettext

	def disable(self):
		self.active = False

		del self._modules
		del self._js
		with contextlib.suppress(AttributeError):
			del self.translationIndex

def init(moduleManager):
	return JSInputTypingLogicModule(moduleManager)
