#! /usr/bin/python3
# -*- coding: utf-8 -*-
#
# Univention Office 365 - cmdline tests
#
# Copyright 2016-2022 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

from __future__ import print_function

import argparse

from typing import List
from univention.office365.microsoft.account import AzureAccount
from univention.office365.microsoft.core import MSGraphApiCore
from univention.office365.microsoft.objects.azureobjects import GroupAzure, UserAzure
from univention.office365.ucr_helper import UCRHelper


def get_members(grp):
	# type: (GroupAzure) -> List[UserAzure]
	members = grp.list_members()
	member_ids = list()
	if not members:
		return list()
	else:
		azure_objs = [x for x in members if isinstance(x, (GroupAzure, UserAzure))]
		if all(isinstance(azure_obj.displayName, str) and azure_obj.displayName.startswith("ZZZ_deleted_") for azure_obj in azure_objs):
			return list()
	return member_ids


if __name__ == "__main__":
	parser = argparse.ArgumentParser(description="List (delete) empty groups ...")
	parser.add_argument("-d", "--delete", action="store_true", help="delete empty groups")
	parser.add_argument("connection", help="connection to use")
	args = parser.parse_args()
	if args.connection not in UCRHelper.get_adconnection_aliases():
		parser.error("choose one of these connections: {}".format(UCRHelper.get_adconnection_aliases()))
	# ucr = ConfigRegistry()
	# ucr.load()
	account = AzureAccount(args.connection)
	core = MSGraphApiCore(account)
	# ah = AzureHandler(ucr, args.connection, args.connection)
	groups = GroupAzure.list(core)
	empty_groups = list()
	for grp in groups:
		if not grp.displayName.startswith('ZZZ_deleted_'):
			print('Name: {displayName} Description: {description} objectId: {objectId}'.format(displayName=grp.displayName, description=grp.description, objectId=grp.id))
			grp.set_core(core)
			members = get_members(grp)
			if members:
				for member in members:
					print('\tMember: {}'.format(member))
			else:
				empty_groups.append(grp)
	if empty_groups:
		print('')
		print('Empty groups:')
		for grp in empty_groups:
			print('Name: {displayName} Description: {description} objectId: {objectId}'.format(displayName=grp.displayName, description=grp.description, objectId=grp.id))
			if args.delete:
				print('\tdelete empty group {displayName} ... '.format(displayName=grp.displayName), end='')
				grp.deactivate()
				print('OK')
