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

/**
 * convert xml dateTime to clasic date time
 *
 * Usage:
 *   value | dateTime
 * Example:
 *   {{ 2016-05-05T17:20:36.85 | dateTime }}
 *   formats to: 17:20:36 5.5.2017
 *
 * {{ 2016-05-05T17:20:36.85 | dateTime : false : 2 }}
 *   formats to: 5.2017
 */
@Pipe({ name: 'dateTime' })
export class DateTimePipe implements PipeTransform {
    transform(value: string, showTime: boolean = true, propNum: number = 3, unitNum: number = 3): string {
        value = (value.lastIndexOf('.') !== -1) ? value.substr(0, value.lastIndexOf('.')) : value;
        if (value) {
            const [date, time] = value.split('T');
            if (date) {
                const [year, month, day] = date.split('-');
                if (time) {
                    const [hour, minutes, seconds] = time.split(':');

                    return `${propNum >= 3 ? `${day}.` : ''}${propNum >= 2 ? `${month}.` : ''}${propNum >= 1 ? year : ''}`
                        + (showTime ? ` ${unitNum >= 1 ? `${hour}:` : ''}${unitNum >= 2 ? `${minutes}` : ''}${unitNum >= 3 ? ':' + seconds : ''}` : ``);
                }
            }
        }

        return value;
    }
}
