import { Component, ChangeDetectionStrategy, Input } from '@angular/core';
import { CustomerService } from '@swagger/crm';
import { ReplaySubject, of, NEVER } from 'rxjs';
import { switchMap, catchError, map, flatMap, filter, throttleTime, distinctUntilChanged } from 'rxjs/operators';
import { isNullOrUndefined } from 'util';

@Component({
  selector: 'app-shelf-details-customer-features',
  templateUrl: 'customer-features.component.html',
  styleUrls: ['customer-features.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CustomerFeaturesComponent {
  @Input()
  set customerNumber(value: string) {
    if (!isNullOrUndefined(value)) {
      this.customernumber$.next(value);
    }
  }

  customernumber$ = new ReplaySubject<string>();

  features$ = this.customernumber$.pipe(
    throttleTime(50),
    distinctUntilChanged(),
    switchMap((customerNumber) =>
      this.customerService
        .CustomerListCustomers({
          input: { qs: customerNumber },
        })
        .pipe(
          catchError((err) => {
            return NEVER;
          }),
          map((response) => {
            return response.result.find((c) => c.customerNumber === customerNumber);
          })
        )
    ),
    filter((customer) => !!customer),
    map((customer) => customer.features || []),
    map((features) => features.filter((f) => f.enabled && !!f.description))
  );

  constructor(private customerService: CustomerService) {}
}
