"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const kms = require("@aws-cdk/aws-kms");
const s3n = require("@aws-cdk/aws-s3-notifications");
const cdk = require("@aws-cdk/cdk");
const policy_1 = require("./policy");
/**
 * Reference to a new or existing Amazon SQS queue
 */
class QueueRef extends cdk.Construct {
    constructor() {
        super(...arguments);
        /**
         * The set of S3 bucket IDs that are allowed to send notifications to this queue.
         */
        this.notifyingBuckets = new Set();
    }
    /**
     * Import an existing queue
     */
    static import(parent, name, props) {
        new ImportedQueue(parent, name, props);
    }
    /**
     * Export a queue
     */
    export() {
        return {
            queueArn: new cdk.Output(this, 'QueueArn', { value: this.queueArn }).makeImportValue(),
            queueUrl: new cdk.Output(this, 'QueueUrl', { value: this.queueUrl }).makeImportValue(),
            keyArn: this.encryptionMasterKey
                ? new cdk.Output(this, 'KeyArn', { value: this.encryptionMasterKey.keyArn }).makeImportValue()
                : undefined
        };
    }
    /**
     * Adds a statement to the IAM resource policy associated with this queue.
     *
     * If this queue was created in this stack (`new Queue`), a queue policy
     * will be automatically created upon the first call to `addToPolicy`. If
     * the queue is improted (`Queue.import`), then this is a no-op.
     */
    addToResourcePolicy(statement) {
        if (!this.policy && this.autoCreatePolicy) {
            this.policy = new policy_1.QueuePolicy(this, 'Policy', { queues: [this] });
        }
        if (this.policy) {
            this.policy.document.addStatement(statement);
        }
    }
    /**
     * Allows using SQS queues as destinations for bucket notifications.
     * Use `bucket.onEvent(event, queue)` to subscribe.
     * @param bucketArn The ARN of the notifying bucket.
     * @param bucketId A unique ID for the notifying bucket.
     */
    asBucketNotificationDestination(bucketArn, bucketId) {
        if (!this.notifyingBuckets.has(bucketId)) {
            this.addToResourcePolicy(new cdk.PolicyStatement()
                .addServicePrincipal('s3.amazonaws.com')
                .addAction('sqs:SendMessage')
                .addResource(this.queueArn)
                .addCondition('ArnLike', { 'aws:SourceArn': bucketArn }));
            // if this queue is encrypted, we need to allow S3 to read messages since that's how
            // it verifies that the notification destination configuration is valid.
            // by setting allowNoOp to false, we ensure that only custom keys that we can actually
            // control access to can be used here as described in:
            // https://docs.aws.amazon.com/AmazonS3/latest/dev/ways-to-add-notification-config-to-bucket.html
            if (this.encryptionMasterKey) {
                this.encryptionMasterKey.addToResourcePolicy(new cdk.PolicyStatement()
                    .addServicePrincipal('s3.amazonaws.com')
                    .addAction('kms:GenerateDataKey')
                    .addAction('kms:Decrypt')
                    .addResource('*'), /* allowNoOp */ false);
            }
            this.notifyingBuckets.add(bucketId);
        }
        return {
            arn: this.queueArn,
            type: s3n.BucketNotificationDestinationType.Queue
        };
    }
}
exports.QueueRef = QueueRef;
/**
 * A queue that has been imported
 */
class ImportedQueue extends QueueRef {
    constructor(parent, name, props) {
        super(parent, name);
        this.autoCreatePolicy = false;
        this.queueArn = props.queueArn;
        this.queueUrl = props.queueUrl;
        if (props.keyArn) {
            this.encryptionMasterKey = kms.EncryptionKey.import(this, 'Key', {
                keyArn: props.keyArn
            });
        }
    }
}
/**
 * URL of a queue
 */
class QueueUrl extends cdk.Token {
}
exports.QueueUrl = QueueUrl;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicXVldWUtcmVmLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsicXVldWUtcmVmLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsd0NBQXlDO0FBQ3pDLHFEQUFzRDtBQUN0RCxvQ0FBcUM7QUFDckMscUNBQXVDO0FBR3ZDOztHQUVHO0FBQ0gsTUFBc0IsUUFBUyxTQUFRLEdBQUcsQ0FBQyxTQUFTO0lBQXBEOztRQWdDSTs7V0FFRztRQUNjLHFCQUFnQixHQUFHLElBQUksR0FBRyxFQUFVLENBQUM7SUFtRTFELENBQUM7SUFyR0c7O09BRUc7SUFDSSxNQUFNLENBQUMsTUFBTSxDQUFDLE1BQXFCLEVBQUUsSUFBWSxFQUFFLEtBQW9CO1FBQzFFLElBQUksYUFBYSxDQUFDLE1BQU0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