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

import argparse, uuid, requests

parser = argparse.ArgumentParser(
    description='       You need to have Python3 and Python Requests lib install to run this script from cmd \n'
                '       To run from IDE, you only need to add Python3 SDK to your project\'s environment \n'
                '       Script creates groups, sub-groups-depth, same level sub-groups and adds equal \n'
                '       Amount of users to the created groups (or just users, with no groups) \n'
                '       For better understanding of naming convention and structure, please refer to this diagram \n'
                '       https://github.com/Alfresco/alfresco-apps/pull/3496#discussion_r812774610 \n',
    formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-g', '--parentGroupCount', default=3, help='Define the number of parent/root groups to be created.')
parser.add_argument('-m', '--sameLevelSubGroupCount', default=4, help='Define the amount of sub-groups on the same level')
parser.add_argument('-s', '--subGroupDepth', default=4, help='Define the depth of sub-groups each parent/root group will have')
parser.add_argument('-u', '--userPerGroup', default=1, help='Define the amount of users per group - each parent, sub-group and same level group will have the same number of users')
parser.add_argument('-l', '--url', default="http://localhost:8080", help='Server Protocol + domain + port with no trailing slash')
parser.add_argument('-n', '--userName', default="admin", help='Basic auth Username')
parser.add_argument('-p', '--password', default="admin", help='Basic auth password')
parser.add_argument('-o', '--usersOnly', default=False, help='Create users only (without groups or sub-groups)')
parser.add_argument('-c', '--userCount', default=10, help='Amount of created users if only users are created (without groups or sub-groups)')
parser.add_argument('-a', '--parentGroupsName', default="Automation-Parent", help='Define the name of parent groups')
parser.add_argument('-r', '--subGroupsName', default="Automation-Sub", help='Define the name of sub-groups')
parser.add_argument('-e', '--usersName', default="Automation-User", help='Define the name of created users')
parser.add_argument('-w', '--depthGroupDelimiter', default="--MAIN--", help='Define the name of sub-groups delimiter')
parser.add_argument('-q', '--sameLevelGroupDelimiter', default="--SAME-LEVEL--", help='Define the name of same level groups delimiter')
args = parser.parse_args()

parentGroupCount = int(args.parentGroupCount)
sameLevelSubGroupCount = int(args.sameLevelSubGroupCount)
sameLevelSubGroupIds = []
subGroupDepth = int(args.subGroupDepth)
usersPerGroup = int(args.userPerGroup)
userCount = int()
groupsEndPoint = args.url + "/alfresco/api/-default-/public/alfresco/versions/1/groups"
peoplesEndPoint = args.url + "/alfresco/api/-default-/public/alfresco/versions/1/people"
basicAuth = auth = (args.userName, args.password)

groupIds = []
subGroupIds = []
userIds = []

def sliceUuid():
    return str(uuid.uuid4())[:7]

def createParentGroups(parentGroupName):
    for i in range(parentGroupCount):
        resp = requests.post(url=groupsEndPoint,
                             json={"id": args.parentGroupsName + "--" + str(i) + "--" + parentGroupName,
                                   "displayName": args.parentGroupsName + "--" + str(i) + "--" + parentGroupName
                                   }, auth=basicAuth)
        groupIds.append(resp.json()['entry']['id'])
        subGroupIds.append(resp.json()['entry']['id'])
        createPersonMembership()


def createSubGroups(subGroupName):
    for i in range(len(groupIds)):
        resp = requests.post(url=groupsEndPoint,
                             json={"id": args.subGroupsName + args.depthGroupDelimiter + str(i) + "--" + subGroupName,
                                   "displayName": args.subGroupsName + args.depthGroupDelimiter + str(i) + "--" + subGroupName,
                                   "parentIds": [groupIds.pop(0)]
                                   }, auth=basicAuth)
        groupIds.append(resp.json()['entry']['id'])
        subGroupIds.append(resp.json()['entry']['id'])
        createPersonMembership()


def createSameLevelSubGroups(subGroupName, subGroupCount):
    for i in range(sameLevelSubGroupCount):
        resp = requests.post(url=groupsEndPoint,
                             json={"id": args.subGroupsName + args.sameLevelGroupDelimiter + str(i) + "--" + subGroupName,
                                   "displayName": args.subGroupsName + args.sameLevelGroupDelimiter + str(i) + "--" + subGroupName,
                                   "parentIds": [subGroupIds[subGroupCount]]
                                   }, auth=basicAuth)
        sameLevelSubGroupIds.append(resp.json()['entry']['id'])
        createPersonMembership()


def createUsers(userId):
    if args.usersOnly:
        userCount = args.userCount
    else:
        userCount = usersPerGroup * (parentGroupCount + (subGroupDepth * sameLevelSubGroupCount * parentGroupCount) + ((subGroupDepth + sameLevelSubGroupCount) * parentGroupCount))
    for i in range(userCount):
        resp = requests.post(url=peoplesEndPoint,
                             json={"id": args.usersName + "--" + str(i) + "--" + userId,
                                   "password": str(uuid.uuid4()),
                                   "firstName": str(uuid.uuid4()),
                                   "lastName": str(uuid.uuid4()),
                                   "email": str(uuid.uuid4())
                                   }, auth=basicAuth)
        userIds.append(resp.json()['entry']['id'])


def createPersonMembership():
    for i in range(usersPerGroup):
        requests.post(groupsEndPoint + "/" + groupIds[-1] + "/members",
                      json={"id": userIds.pop(0),
                            "memberType": "PERSON"
                            }, auth=basicAuth)

createUsers(sliceUuid())

if not args.usersOnly:
    createParentGroups(sliceUuid())
    for i in range(subGroupDepth):
        createSubGroups(sliceUuid())
    for i in range(len(subGroupIds)):
        createSameLevelSubGroups(sliceUuid(), i)
