import * as cdk from "@aws-cdk/core";
import { GrafanaPermissions } from "./grafana-permissions";
import { FlowLogs } from "./flow-logs";
import { WorkerAlarms } from "./worker-alarms";
import { AlarmSNSTopics } from "./alarm-sns-topics";
import { EnvName } from "../../env-names";
import {createDefaultAlarmsForApi} from "../shared";
import {Duration} from "@aws-cdk/core";

export interface MetricsStackProps extends cdk.StackProps {
  readonly vpcID: string;
  readonly envName: EnvName;
}

/**
 * MetricsStack contains resources related to our metrics stack - CloudWatch,
 * CloudWatch dashboards, Grafana.
 */
export class MetricsStack extends cdk.Stack {
  readonly cloudwatchAlarmSNSTopics: AlarmSNSTopics;

  constructor(scope: cdk.Construct, id: string, props: MetricsStackProps) {
    super(scope, id, props);

    new GrafanaPermissions(this, "GrafanaPermissions");

    // Enable flow logs on the VPC.
    new FlowLogs(this, "FlowLogs", {
      vpcID: props.vpcID
    });

    this.cloudwatchAlarmSNSTopics = new AlarmSNSTopics(this, "AlarmSNSTopics", {
      envName: props.envName
    });

    // Add CloudWatch alarms that alarm if Autohost Worker stops hosting or unhosting.
    // (Autohost Worker is currently only in the production env.)
    if (props.envName === EnvName.Production) {
      new WorkerAlarms(this, "WorkerAlarms", {
        cloudwatchAlarmSNSTopics: this.cloudwatchAlarmSNSTopics,
        stageDimension: "production"
      });
    }

    // Create alarms for GetEndorsedChannels
    let serviceProps = {
      environmentName: props.envName,
      cloudwatchAlarmSNSTopics: this.cloudwatchAlarmSNSTopics,
      region: this.region,
      serviceName: "Autohost Server",
    }
    createDefaultAlarmsForApi(this, "GetEndorsedChannels", serviceProps, Duration.seconds(.15), 3);
  }
}
