import { NamespaceCache, AWSTagSet } from '../../interfaces/tagcache';
import { SensuTagSet } from '../../interfaces/sensu';

const TagWhitelist = [
  new RegExp('^Litany.*$'),
  new RegExp('^Name$'),
  new RegExp('^VolumeType$'),
  new RegExp('^Iops$'),
]

export class Cacher {
  public get(dimensions: AWS.CloudWatch.Types.Dimensions, cache: NamespaceCache): SensuTagSet {
    throw new Error("You must implement the get() method");
  };

  public async fill(): Promise<NamespaceCache> {
    throw new Error("You must implement the fill() method");
  };

  public arn_builder(service: string, arn_suffix: string): string {
    return 'arn:aws:' + service + ':' + process.env.AWS_REGION + ':' + process.env.AWSAccountId + ':' + arn_suffix
  };

  public mergeTags(tags: AWSTagSet): SensuTagSet {
    let res: SensuTagSet = {};

    for (let j = 0; j < tags.length; j++) {
      res[tags[j].Key] =
        tags[j].Value;
    }

    return this.filterTags(res);
  }

  public unMergeTags(tags: SensuTagSet): AWSTagSet {
    let res: AWSTagSet = [];

    for (let t of Object.keys(tags)) {
      res.push({Key: t, Value: tags[t]})
    }

    return res;
  }

  public filterTags(tags: SensuTagSet): SensuTagSet {
    for (let tagName of Object.keys(tags)) {
      if (!TagWhitelist.some(r => { return r.test(tagName) })) {
        delete tags[tagName];
      }
    }
    return tags;
  }

  public mergeDimensions(dimensions: AWS.CloudWatch.Types.Dimensions): SensuTagSet {
    let res: SensuTagSet = {};

    for (let j = 0; j < dimensions.length; j++) {
      res[dimensions[j].Name] =
        dimensions[j].Value;
    }

    return res;
  }
}
