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

export class LambdaTags extends Cacher {

  lambda: AWS.Lambda;

  constructor() {
    super()
    this.lambda = new AWS.Lambda();
  }

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

    if (d.FunctionName) {
      functionTags = [].concat.apply([], cache.Dimension.Functions.filter(t => {
        return (t.FunctionName === d.FunctionName);
      }).map(t => { return t.Tags }))
    }

    return this.mergeTags(functionTags);
  }

  public async fill() {

    let functions: { FunctionName: string, Tags: AWSTagSet }[] = [];

    let promise: Promise<void[]> = this.lambda.listFunctions().promise().then(data => {
      return Promise.all(data.Functions.map((func) => {
        return this.lambda.listTags({ Resource: func.FunctionArn }).promise().then(tags => {
          functions.push({ FunctionName: func.FunctionName, Tags: this.unMergeTags(tags.Tags) })
        })
      }))
    })

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