import { Pipe, PipeTransform } from '@angular/core';
import pxd from 'parse-xsd-duration';

/**
 * Convert duration string to reasonable time string
 *
 * Usage:
 *   value | duration
 * Example:
 *   {{ 'PT23H59M' | duration }}
 *   return 23:59
 */
@Pipe({ name: 'duration' })
export class DurationPipe implements PipeTransform {
    transform(value: string): string {
        const obj = pxd(value, true);
        if (!obj['hours']) {
            obj['hours'] = 0;
        }
        if (!obj['minutes']) {
            obj['minutes'] = 0;
        }
        const hours = obj.hours.toString();
        let minutes = obj.minutes.toString();
        if (minutes.length === 1) {
            minutes = '0' + minutes;
        }

        return hours + ':' + minutes;
    }
}
