import {
  AnalyticalScope,
  DateTimePicker,
  DateTimeUtil,
  DateValueType,
  Filter,
  FilterComponent,
  FilterOperation,
  FilterUtil
} from "@webbpm/base-package";
import {Moment} from "moment-timezone";

@AnalyticalScope(DateTimePicker)
export class CurrentDateWithShiftFilterComponent extends FilterComponent {
  public shift: number;
  private dateTimePicker: DateTimePicker;

  public initialize(): void {
    super.initialize();
    this.dateTimePicker = this.getScript(DateTimePicker);
  }

  getFilter(): Filter {
    if (!this.dateTimePicker) {
      return null;
    }

    const value: Moment = this.dateTimePicker.isValueEmpty()
                          ? DateTimeUtil.getCurrentDateInMidnight().add(this.shift, 'years')
                          : this.dateTimePicker.getValueAsMoment().clone();

    let filterValue: string;
    const dateValueType: DateValueType = this.dateTimePicker.getDateValueType();
    switch (dateValueType) {
      case DateValueType.DATE:
        switch (this.operation) {
          case FilterOperation.GREATER_THAN:
          case FilterOperation.LESS_OR_EQUAL:
            value.hours(23);
            value.minutes(59);
            value.seconds(59);
            value.milliseconds(999);
            filterValue = DateTimeUtil.transformToString(value);
            break;
          default:
            filterValue = DateTimeUtil.formatToDate(value);
            break;
        }
        break;
      case DateValueType.DATETIME:
        filterValue = DateTimeUtil.formatToTimestamp(value);
        break;
    }

    return FilterUtil.singleValueFilter(this.getObjectId(), filterValue, this.operation);
  }
}
