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

export class ESTags extends Cacher {

  es: AWS.ES;

  constructor() {
    super()
    this.es = new AWS.ES();
  }

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

    esTags = [].concat.apply([], cache.Dimension.Domains.filter(t => {
      return (t.DomainName === d.DomainName);
    }).map(t => { return t.Tags }))

    return this.mergeTags(esTags);
  }

  public async fill() {

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

    let promise: Promise<void[]> = this.es.listDomainNames().promise().then(data => {
      return Promise.all(data.DomainNames.map((domain) => {
        let arn = this.arn_builder('es', 'domain/' + domain.DomainName);
        return this.es.listTags({ ARN: arn }).promise().then(tags => {
          domains.push({ DomainName: domain.DomainName, Tags: tags.TagList })
        })
      }))
    })

    return promise.then(() => {
      let cache: NamespaceCache = {
        LastUpdated: new Date(),
        Dimension: {
          Domains: domains,
        }
      };
      return cache;
    });
  }
}
