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

export class EBSTags extends Cacher {

  ec2: AWS.EC2;

  constructor() {
    super()
    this.ec2 = new AWS.EC2();
  }

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

    let ebsTags = [].concat.apply([], cache.Dimension.Volumes.filter(t => {
      return (t.VolumeId === d.VolumeId);
    }).map(t => {
      t.Tags.push({ Key: 'VolumeType', Value: t.VolumeType });
      t.Tags.push({ Key: 'Iops', Value: t.Iops });
      return t.Tags;
    }));

    return this.mergeTags(ebsTags);
  }

  public async fill() {
    let ebsGet = this.ec2.describeVolumes().promise().then(resp => {
      return [].concat.apply([], resp.Volumes.map(v => {
        return { VolumeId: v.VolumeId, Tags: v.Tags, VolumeType: v.VolumeType, Iops: v.Iops }
      }));
    });

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

  }
}
