import AWS = require('aws-sdk');
import { Cacher } from './base';
import { NamespaceCache } from '../../interfaces/tagcache';
import { SensuTagSet } from '../../interfaces/sensu';

export class ASGTags extends Cacher {

  asg: AWS.AutoScaling;

  constructor() {
    super()
    this.asg = new AWS.AutoScaling();
  }

  public get(dimensions: AWS.CloudWatch.Types.Dimensions, cache: NamespaceCache): SensuTagSet {
    let d = this.mergeDimensions(dimensions);
    let asgTags = [];

    if (d.AutoScalingGroupName) {
      asgTags = [].concat.apply([], cache.Dimension.AutoScalingGroups.filter(t => {
        return (t.AutoScalingGroupName === d.AutoScalingGroupName);
      }).map(t => { return t.Tags }))
    }

    return this.mergeTags(asgTags);
  }

  public async fill() {
    let asgGet = this.asg.describeAutoScalingGroups().promise().then(resp => {
      return [].concat.apply([], resp.AutoScalingGroups.map(a => {
        return { AutoScalingGroupName: a.AutoScalingGroupName, Tags: a.Tags }
      }));
    });

    return asgGet.then(d => {
      let cache: NamespaceCache = {
        LastUpdated: new Date(),
        Dimension: {
          AutoScalingGroups: d,
        }
      };
      return cache;
    });

  }
}
