import { Pipe, PipeTransform } from '@angular/core';
import { ConfigService } from '@shared/config/config.service';
import { DatePipe } from '@angular/common';

@Pipe({
  name: 'dateFormatter'
})
export class DateFormatterPipe implements PipeTransform {
  private datePipe: DatePipe;
  _locale = undefined;

  constructor(private config: ConfigService) {
    this._locale = this.config.locale;
    this.datePipe = new DatePipe(this._locale);
  }

  transform(value: any, format?: string, locale?: string): string | null {
    if (!value) {
      return $localize`n/a`;
    }
    if (!format) {
      format = this.config.authService.dateFormat;
    }
    if (!locale) {
      locale = this._locale;
    }
    let timezone: string;
    value = String(value);
    if (value.includes('T')) {
      if (value.endsWith('Z')) {
        timezone = 'UTC';
      } else if (value.indexOf('+') > -1) {
        const split = value.split('+');
        timezone = split[1].replace(':', '');
        timezone = `+${timezone}`;
      } else if (value.indexOf('-') > -1) {
        const split = value.split('-');
        timezone = split[split.length - 1].replace(':', '');
        timezone = `-${timezone}`;
      }
    }
    return this.datePipe.transform(value, format, timezone, locale);
  }

  toDateTime(value: any): string | null {
    return this.transform(value, this.config.authService.dateTimeFormat);
  }

  getTitleAttributeValue(value: any): string | null {
    return this.transform(value, 'y-MM-dd HH:mm:ss z');
  }

  getDate(value: any): string | null {
    return this.transform(value, 'y-MM-dd');
  }

}
