#!/usr/share/ucs-test/runner python
## -*- coding: utf-8 -*-
## desc: set values in extended attribute (Bug 41707)
## tags: [apptest,ucsschool,skip_in_multiserver,ucsschool_import]
## roles: [domaincontroller_master]
## exposure: dangerous
## packages:
##   - ucs-school-import
## bugs: [41707]

import time
import copy
import pprint
import univention.testing.strings as uts
from essential.importusers_cli_v2 import CLI_Import_v2_Tester
from essential.importusers import Person


class Test(CLI_Import_v2_Tester):

	def __init__(self):
		super(Test, self).__init__()
		self.ou_B = None
		self.ou_C = None

	def test(self):  # formally test_create_modify_with_extended_attribute()
		"""
		Bug #41707: set values in extended attribute
		"""

		ext_attr_name = uts.random_name()
		properties = {
			'position': self.udm.UNIVENTION_CONTAINER,
			'name': uts.random_name(),
			'shortDescription': uts.random_string(),
			'CLIName': ext_attr_name,
			'module': 'users/user',
			'objectClass': 'univentionFreeAttributes',
			'ldapMapping': 'univentionFreeAttribute15'
		}
		self.udm.create_object('settings/extended_attribute', **properties)

		for role in ('student', 'teacher', 'staff', 'teacher_and_staff'):
			self.log.info('*** Importing a new single user with role %r with ', role)

			source_uid = 'sourceUID-%s' % (uts.random_string(),)

			config = copy.deepcopy(self.default_config)
			config.update_entry('sourceUID', source_uid)
			config.update_entry('csv:mapping:extattr', ext_attr_name)
			config.update_entry('csv:mapping:Benutzername', 'username')
			config.update_entry('csv:mapping:recordUID', 'record_uid')
			config.update_entry('scheme:recordUID', '<username>')
			config.update_entry('scheme:%s' % (ext_attr_name,), "<firstname:upper> <lastname> <description>")
			config.update_entry('sourceUID', source_uid)
			config.update_entry('user_role', role)

			class ExtAttrPerson(Person):
				def __init__(self, school, role):
					Person.__init__(self, school, role)
					self.extattr = time.strftime('%Y-%m-%d')

				def map_to_dict(self, value_map):
					result = Person.map_to_dict(self, value_map)
					result[value_map.get(ext_attr_name, '__EMPTY__')] = self.extattr
					return result

				def expected_attributes(self):
					result = Person.expected_attributes(self)
					result['univentionFreeAttributes15'] = [self.extattr]

			# create person with extended attribute (today)
			person = ExtAttrPerson(self.ou_A.name, role)
			self.log.info('ext_attr_name=%r extattr value=%r', ext_attr_name, person.extattr)
			person.update(record_uid=person.username, source_uid=source_uid)
			fn_csv = self.create_csv_file(person_list=[person], mapping=config['csv']['mapping'])
			fn_config = self.create_config_json(config=config)
			# start import
			self.run_import(['-c', fn_config, '-i', fn_csv])

			self.log.debug('User object %r:\n%s', person.dn, pprint.PrettyPrinter(indent=2).pformat(self.lo.get(person.dn)))
			person.verify()

			# modify person and set ext_attr to random value
			person.update(extattr=uts.random_string())
			fn_csv = self.create_csv_file(person_list=[person], mapping=config['csv']['mapping'])
			fn_config = self.create_config_json(config=config)
			# start import
			self.run_import(['-c', fn_config, '-i', fn_csv])

			self.log.debug('User object %r:\n%s', person.dn, pprint.PrettyPrinter(indent=2).pformat(self.lo.get(person.dn)))
			person.verify()


def main():
	tester = Test()
	try:
		tester.run()
	finally:
		tester.cleanup()


if __name__ == '__main__':
	main()
