"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const commands_1 = require("../../commands");
const request_1 = require("../../../../request");
const GraphItemsListCommand_1 = require("../../../base/GraphItemsListCommand");
const vorpal = require('../../../../vorpal-init');
class AadO365GroupListCommand extends GraphItemsListCommand_1.GraphItemsListCommand {
    get name() {
        return `${commands_1.default.O365GROUP_LIST}`;
    }
    get description() {
        return 'Lists Office 365 Groups in the current tenant';
    }
    getTelemetryProperties(args) {
        const telemetryProps = super.getTelemetryProperties(args);
        telemetryProps.displayName = typeof args.options.displayName !== 'undefined';
        telemetryProps.mailNickname = typeof args.options.mailNickname !== 'undefined';
        telemetryProps.includeSiteUrl = args.options.includeSiteUrl;
        telemetryProps.deleted = args.options.deleted;
        telemetryProps.orphaned = args.options.orphaned;
        return telemetryProps;
    }
    commandAction(cmd, args, cb) {
        const groupFilter = `?$filter=groupTypes/any(c:c+eq+'Unified')`;
        const displayNameFilter = args.options.displayName ? ` and startswith(DisplayName,'${encodeURIComponent(args.options.displayName).replace(/'/g, `''`)}')` : '';
        const mailNicknameFilter = args.options.mailNickname ? ` and startswith(MailNickname,'${encodeURIComponent(args.options.mailNickname).replace(/'/g, `''`)}')` : '';
        const expandOwners = args.options.orphaned ? '&$expand=owners' : '';
        const topCount = '&$top=100';
        let endpoint = `${this.resource}/v1.0/groups${groupFilter}${displayNameFilter}${mailNicknameFilter}${expandOwners}${topCount}`;
        if (args.options.deleted) {
            endpoint = `${this.resource}/v1.0/directory/deletedItems/Microsoft.Graph.Group${groupFilter}${displayNameFilter}${mailNicknameFilter}${topCount}`;
        }
        this
            .getAllItems(endpoint, cmd, true)
            .then(() => {
            if (args.options.orphaned) {
                const orphanedGroups = [];
                this.items.forEach((group, index) => {
                    if (!group.owners || group.owners.length === 0) {
                        orphanedGroups.push(group);
                    }
                });
                this.items = orphanedGroups;
            }
            if (args.options.includeSiteUrl) {
                return Promise.all(this.items.map(g => this.getGroupSiteUrl(g.id, cmd)));
            }
            else {
                return Promise.resolve();
            }
        })
            .then((res) => {
            if (res) {
                res.forEach(r => {
                    for (let i = 0; i < this.items.length; i++) {
                        if (this.items[i].id !== r.id) {
                            continue;
                        }
                        this.items[i].siteUrl = r.url;
                        break;
                    }
                });
            }
            if (args.options.output === 'json') {
                cmd.log(this.items);
            }
            else {
                cmd.log(this.items.map(g => {
                    const group = {
                        id: g.id,
                        displayName: g.displayName,
                        mailNickname: g.mailNickname
                    };
                    if (args.options.deleted) {
                        group.deletedDateTime = g.deletedDateTime;
                    }
                    if (args.options.includeSiteUrl) {
                        group.siteUrl = g.siteUrl;
                    }
                    return group;
                }));
            }
            if (this.verbose) {
                cmd.log(vorpal.chalk.green('DONE'));
            }
            cb();
        }, (err) => this.handleRejectedODataJsonPromise(err, cmd, cb));
    }
    getGroupSiteUrl(groupId, cmd) {
        return new Promise((resolve, reject) => {
            const requestOptions = {
                url: `${this.resource}/v1.0/groups/${groupId}/drive?$select=webUrl`,
                headers: {
                    accept: 'application/json;odata.metadata=none'
                },
                json: true
            };
            request_1.default
                .get(requestOptions)
                .then((res) => {
                resolve({
                    id: groupId,
                    url: res.webUrl ? res.webUrl.substr(0, res.webUrl.lastIndexOf('/')) : ''
                });
            }, (err) => {
                reject(err);
            });
        });
    }
    options() {
        const options = [
            {
                option: '-d, --displayName [displayName]',
                description: 'Retrieve only groups with displayName starting with the specified value'
            },
            {
                option: '-m, --mailNickname [displayName]',
                description: 'Retrieve only groups with mailNickname starting with the specified value'
            },
            {
                option: '--includeSiteUrl',
                description: 'Set to retrieve the site URL for each group'
            },
            {
                option: '--deleted',
                description: 'Set to only retrieve deleted groups'
            },
            {
                option: '--orphaned',
                description: 'Set to only retrieve groups without owners'
            }
        ];
        const parentOptions = super.options();
        return options.concat(parentOptions);
    }
    validate() {
        return (args) => {
            if (args.options.deleted && args.options.includeSiteUrl) {
                return 'You can\'t retrieve site URLs of deleted Office 365 Groups';
            }
            return true;
        };
    }
    commandHelp(args, log) {
        const chalk = vorpal.chalk;
        log(vorpal.find(this.name).helpInformation());
        log(`  Remarks:

    Using the ${chalk.blue('--includeSiteUrl')} option, you can retrieve the URL
    of the site associated with the particular Office 365 Group. If you however
    retrieve too many groups and will try to get their site URLs, you will most
    likely get an error as the command will get throttled, issuing too many
    requests, too frequently. If you get an error, consider narrowing down
    the result set using the ${chalk.blue('--displayName')} and ${chalk.blue('--mailNickname')} filters.
    
    Retrieving the URL of the site associated with the particular
    Office 365 Group is not possible when retrieving deleted groups.

    Using the ${chalk.blue('--orphaned')} option, you can retrieve Office 365 Groups without
    owners.

  Examples:
  
    List all Office 365 Groups in the tenant
      ${this.name}

    List Office 365 Groups with display name starting with ${chalk.grey(`Project`)}
      ${this.name} --displayName Project

    List Office 365 Groups mail nick name starting with ${chalk.grey(`team`)}
      ${this.name} --mailNickname team

    List deleted Office 365 Groups with display name starting with ${chalk.grey(`Project`)}
      ${this.name} --displayName Project --deleted

    List deleted Office 365 Groups with mail nick name starting with ${chalk.grey(`team`)}
      ${this.name} --mailNickname team --deleted

    List Office 365 Groups with display name starting with ${chalk.grey(`Project`)} including
    the URL of the corresponding SharePoint site
      ${this.name} --displayName Project --includeSiteUrl

    List Office 365 Groups without owners
      ${this.name} --orphaned
`);
    }
}
module.exports = new AadO365GroupListCommand();
//# sourceMappingURL=o365group-list.js.map