import { Pipe, PipeTransform } from '@angular/core';

/**
 * Convert xml datetime (iso-8601 format) to clasic date
 *
 * Usage:
 *   value | xmlDateTime
 * Example:
 *   {{ PT16H30M | xmlDateTime }}
 *   formats to: 16:30
 */
@Pipe({ name: 'xmlDateTime' })
export class XmlDateTimePipe implements PipeTransform {
    transform(value: string): string {
        const dtData = this.getDateTimeDataObject(value);
        const date: string = (dtData.years && dtData.months && dtData.days) ? `${dtData.days}. ${dtData.months}. ${dtData.years}` : '';

        return `${date}${dtData.hours}:${dtData.minutes || '00'}${dtData.seconds ? `:${dtData.seconds}` : ''}`;
    }

    /**
     * It return object of parsed year, month, week, dys, hour, minute and second using regex
     *
     * @param {string} duration (iso-8601 format)
     * @returns {any}
     */
    private getDateTimeDataObject(duration: string): any {
        const regex = /P((([0-9]*\.?[0-9]*)Y)?(([0-9]*\.?[0-9]*)M)?(([0-9]*\.?[0-9]*)W)?(([0-9]*\.?[0-9]*)D)?)?(T(([0-9]*\.?[0-9]*)H)?(([0-9]*\.?[0-9]*)M)?(([0-9]*\.?[0-9]*)S)?)?/;
        const matches = duration.match(regex);

        return {
            years: parseFloat(matches[3]),
            months: parseFloat(matches[5]),
            weeks: parseFloat(matches[7]),
            days: parseFloat(matches[9]),
            hours: parseFloat(matches[12]),
            minutes: parseFloat(matches[14]),
            seconds: parseFloat(matches[16])
        };
    }
}
