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

export class KinesisTags extends Cacher {

  kinesis: AWS.Kinesis;

  constructor() {
    super()
    this.kinesis = new AWS.Kinesis();
  }

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

    kinesisTags = [].concat.apply([], cache.Dimension.Streams.filter(t => {
      return (t.StreamName === d.StreamName);
    }).map(t => { return t.Tags }))

    return this.mergeTags(kinesisTags);
  }

  public async fill() {

    let streams: { StreamName: string, Tags: AWSTagSet }[] = [];
    let tagPromises: Promise<void>[] = [];

    await new Promise((resolve, reject) => {
      this.kinesis.listStreams().eachPage((err: any, data) => {
        if (err) {
          console.log(err);
          reject();
          return false;
        }

        if (data === null) {
          resolve();
          return true;
        }

        for (let stream of data.StreamNames) {
          streams.push({ StreamName: stream, Tags: [] });
        }
        return true;
      });
    });

    for (let stream of streams) {
      tagPromises.push(this.kinesis.listTagsForStream({ StreamName: stream.StreamName }).promise().then(data => {
        stream.Tags = data.Tags as AWSTagSet;
      }))
    }

    return Promise.all(tagPromises).then(() => {
      let cache: NamespaceCache = {
        LastUpdated: new Date(),
        Dimension: {
          Streams: streams,
        }
      };
      return cache;
    });
  }
}
