import {Pipe, PipeTransform} from '@angular/core';
import {SCRange, isInRange, SCISO8601DateRange} from '@openstapps/core';
import {merge, Observable, timer} from 'rxjs';
import {distinctUntilChanged, map, startWith} from 'rxjs/operators';

@Pipe({
  name: 'isInRange',
  pure: true,
  standalone: true,
})
export class InRangePipe implements PipeTransform {
  transform<T>(value: T, range: SCRange<T>): boolean {
    return isInRange(value, range);
  }
}

@Pipe({
  name: 'toDateRange',
  pure: true,
  standalone: true,
})
export class ToDateRangePipe implements PipeTransform {
  transform(value: SCISO8601DateRange): SCRange<Date> {
    return Object.fromEntries(Object.entries(value).map(([key, value]) => [key, new Date(value)]));
  }
}

@Pipe({
  name: 'isInRangeNow',
  pure: true,
  standalone: true,
})
export class InRangeNowPipe implements PipeTransform {
  transform(value: SCRange<Date>): Observable<boolean> {
    return merge(timer(value.lte || value.lt || 0), timer(value.gte || value.gt || 0)).pipe(
      startWith(0),
      map(() => isInRange(new Date(), value)),
      distinctUntilChanged(),
    );
  }
}
