import {DateTimeUtil, DefaultValueFormatter, GridValueFormatter} from "@webbpm/base-package";
import {ValueFormatterParams} from "ag-grid-community";

export class ClientDateTimeFormatter extends DefaultValueFormatter implements GridValueFormatter {

  public dateFormat: string = '';

  format(params: ValueFormatterParams): string {
    if (this.isValueEmpty(params)) {
      return super.format(params);
    }

    // don't apply formatter to row with aggregation function
    if (params.node.isRowPinned()) {
      return params.value;
    }

    if (!this.dateFormat) {
      return ClientDateTimeFormatter.parseForClientTimeZoneAndFormat(params.value, DateTimeUtil.TIMESTAMP_FORMAT);
    }

    if (!ClientDateTimeFormatter.isValidFormat(this.dateFormat)) {
      throw new Error('Invalid date format = ' + this.dateFormat);
    }

    return ClientDateTimeFormatter.parseForClientTimeZoneAndFormat(params.value, this.dateFormat);
  }

  private static isValidFormat(format: string): boolean {
    const validCharsRegex = /^[YyMmDdHhSsTZ.:\[\] -]*$/;
    return format && validCharsRegex.test(format);
  }

  private static parseForClientTimeZoneAndFormat(value: string, dateFormat: string): string {
    let timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    return DateTimeUtil.parseIsoDateTime(value).tz(timezone).format(dateFormat);
  }
}