import { Pipe, PipeTransform } from '@angular/core'
import { DomSanitizer } from '@angular/platform-browser'

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value): any {
    let keys = []
    for (let key in value) {
      keys.push(key)
    }
    return keys
  }
}

@Pipe({name: 'values'})
export class ValuesPipe implements PipeTransform {
  transform(value): any {
    let items = []
    for (let key in value) {
      items.push(value[key])
    }
    return items
  }
}

@Pipe({name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform  {
  constructor(private sanitized: DomSanitizer) {}
  transform(value) {
    return this.sanitized.bypassSecurityTrustHtml(value)
  }
}

@Pipe({name: 'orderBy'})
export class OrderByPipe implements PipeTransform {
  transform(array: any[], field: string): any {
    if (!Array.isArray(array)) {
      return;
    }
    array.sort((a: any, b: any) => {
      if (a[field] < b[field]) {
        return -1;
      } else if (a[field] > b[field]) {
        return 1;
      } else {
        return 0;
      }
    });
    return array;
  }
}