#!/usr/bin/python
# -*- coding: utf-8 -*-

__author__ = "Binh Vu <binh@toan2.com>"

import os, json

from ..util import getlogger
from ..git.git import Git
from .postprocess import PostProcess
"""
	
	Torch module

"""
class Module(object):

	def __init__(self, location):
		self.location = os.path.abspath(location)

		if not os.path.exists(self.location):
			raise "Module directory does not exists ({0})".format(self.location)

		self.logger = getlogger("torch.module")

	@staticmethod
	def isTorchModule(conf):
		return conf["host"].find(".git") != -1

	def getDependencies(self):
		modules = []

		with open(os.path.join(self.location, "composer.json")) as f:
			composer = json.loads(f.read())
			if "dependencies" not in composer:
				composer["dependencies"] = {}

			for package, conf in composer["dependencies"].iteritems():
				conf["name"] = package

				if Module.isTorchModule(conf):
					modules.append(conf)

		return modules


	"""
		Check if module is a valid torch module

		@return (boolean, string) result and an explanation 
	"""
	def verify(self):
		if not Git.isGitRepo(self.location):
			return False, "Not a git repo"

		if os.listdir(self.location) == []:
			return False, "Empty directory"

		if not os.path.exists(os.path.join(self.location, "composer.json")):
			return False, "Missing composer.json " + os.path.join(self.location, "composer.json")

		return True, ""

	"""
		Try to update module working tree to specific brand, commit or tag
	"""
	def updateModuleStatus(self, gitconfig):
		return True, ""

	def updateModuleConfig(self, modules):
		if os.path.exists(os.path.join(self.location, "__init__.py")):
			mode = "r+b"
		else:
			mode = "w+b"
		with open(os.path.join(self.location, "__init__.py"), mode) as f:
			content = f.read()
			content = content.split("\n")

			if content[0].find("# Auto generated by torchrs") != 0:
				self.logger.debug("Not detect torch config, generating ...")

				update = [
					"# Auto generated by torchrs",
					"import os, json", 
					"""with open("{0}/modules.json", "r") as f:""".format(self.location),
					"\tfor mo in json.loads(f.read()):",
					"\t\t__path__.append(mo)",
					"# Auto generated by torchrs"
				]
			else:
				update = []

			content = "\n".join(update + content)

			self.logger.debug("Update __init__.py")
			f.seek(0)
			f.write(content)

		self.logger.debug("Update modules.json")
		with open(os.path.join(self.location, "modules.json"), "w+b") as f:
			f.write(json.dumps(modules, sort_keys=True, indent=4, separators=(',', ': ')))

		self.logger.debug("Update .gitignore")
		if not os.path.exists(os.path.join(self.location, ".gitignore")):
			mode = "w+b"
		else:
			mode = "r+b"
		with open(os.path.join(self.location, ".gitignore"), mode) as f:
			content = f.read()
			content = content.split("\n")

			ignoreFiles = {
				"/modules": 1,
				"*.pyc": 1
			}
			for line in content:
				for key in ignoreFiles:
					if line.strip() == key:
						ignoreFiles[key] = 0
			for key, value in ignoreFiles.iteritems():
				if value == 1:
					f.write(key + "\n")

	def postProcess(self, config, extra):
		processor = PostProcess(self)
		processor.execute(config, extra)