# -*- coding: utf-8 -*-

def updateWIMConfig(self, productId):
	import os.path
	from OPSI.Backend.Backend import OPSI_GLOBAL_CONF
	from OPSI.Types import forceProductId
	from OPSI.Util import getfqdn

	if not productId:
		raise ValueError("Missing productId: {0!r}".format(productId))

	productId = forceProductId(productId)

	if not self.product_getObjects(id=productId):
		from OPSI.Types import BackendMissingDataError

		raise BackendMissingDataError("No product with ID {0!r}".format(productId))

	depotId = getfqdn(conf=OPSI_GLOBAL_CONF)
	if not self.productOnDepot_getObjects(depotId=depotId, productId=productId):
		from OPSI.Types import BackendMissingDataError

		raise BackendMissingDataError("No product {0!r} on {1!r}".format(productId, depotId))

	depot = self.host_getObjects(id=depotId, type="OpsiDepotserver")
	depot = depot[0]
	logger.debug("Working with {0}".format(depot))

	depotPath = depot.depotLocalUrl
	if not depotPath.startswith(u'file://'):
		raise ValueError("Unable to handle the depot remote local url {0!r}.".format(depotPath))

	depotPath = depotPath[7:]
	logger.debug(u"Created path {0!r}".format(depotPath))
	productPath = os.path.join(depotPath, productId)
	wimPath = os.path.join(productPath, 'installfiles', 'sources', 'install.wim')

	if not os.path.exists(wimPath):
		raise RuntimeError("Could not find {0!r}. Aborting!".format(wimPath))

	self.updateWIMConfigFromPath(wimPath, productId)

def updateWIMConfigFromPath(self, path, targetProductId):
	import itertools
	from OPSI.Util.WIM import parseWIM, writeImageInformation

	images = parseWIM(path)

	if targetProductId:
		defaultLanguage = set([image.default_language for image in images if image.default_language])
		if 1 == len(defaultLanguage):
			defaultLanguage = defaultLanguage.pop()
		else:
			if len(defaultLanguage) > 1:
				logger.info("Multiple default languages: {0}".format(defaultLanguage))
				logger.info("Not setting a default.")
			else:
				logger.info("Unable to find a default language.")

			defaultLanguage = None

		writeImageInformation(self, targetProductId, [image.name for image in images],
								list(set(itertools.chain(*[image.languages for image in images if image.languages]))),
								defaultLanguage)
