"use strict";
/*
 *  Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *  SPDX-License-Identifier: Apache-2.0
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.RSWVpc = void 0;
const aws_ec2_1 = require("aws-cdk-lib/aws-ec2");
const aws_iam_1 = require("aws-cdk-lib/aws-iam");
const aws_logs_1 = require("aws-cdk-lib/aws-logs");
const constructs_1 = require("constructs");
class RSWVpc extends constructs_1.Construct {
    constructor(scope, id, props) {
        const { vpcId, albSubnetIds, ecsSubnetIds } = props;
        super(scope, id);
        this.vpc = vpcId === '' ? new aws_ec2_1.Vpc(this, 'MainVPC', {}) : aws_ec2_1.Vpc.fromLookup(this, 'MainVPC', { vpcId });
        const logGroup = new aws_logs_1.LogGroup(this, 'VpcFlowLogGroup', { retention: aws_logs_1.RetentionDays.TEN_YEARS });
        const role = new aws_iam_1.Role(this, 'VpcFlowLogRole', {
            assumedBy: new aws_iam_1.ServicePrincipal('vpc-flow-logs.amazonaws.com')
        });
        // eslint-disable-next-line no-new
        new aws_ec2_1.FlowLog(this, 'VpcFlowLog', {
            resourceType: aws_ec2_1.FlowLogResourceType.fromVpc(this.vpc),
            destination: aws_ec2_1.FlowLogDestination.toCloudWatchLogs(logGroup, role)
        });
        // if only ecs or alb subnets are defined - use them for both alb and ecs
        this.albSubnetSelection = this._getSubnetSelection(scope, !albSubnetIds.length ? ecsSubnetIds : albSubnetIds, aws_ec2_1.SubnetType.PUBLIC);
        this.ecsSubnetSelection = this._getSubnetSelection(scope, !ecsSubnetIds.length ? albSubnetIds : ecsSubnetIds, aws_ec2_1.SubnetType.PRIVATE_WITH_NAT);
    }
    _getSubnetSelection(scope, subnetIds, subnetType) {
        if (!subnetIds.length) {
            return this.vpc.selectSubnets({
                subnetType
            });
        }
        const subnetPrefix = subnetType === aws_ec2_1.SubnetType.PUBLIC ? 'ALB' : 'ECS';
        const subnets = [];
        let subnetCount = 1;
        subnetIds.forEach(function (subnetId) {
            const subnet = aws_ec2_1.Subnet.fromSubnetId(scope, `RSW${subnetPrefix}Subnet${subnetCount}`, subnetId);
            subnets.push(subnet);
            subnetCount++;
        });
        return {
            subnets
        };
    }
}
exports.RSWVpc = RSWVpc;
//# sourceMappingURL=RSWVpc.js.map