import { Select } from '@ngxs/store';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject, Observable } from 'rxjs';
import { EditCustomerData } from '../../../../core/models/edit-customer.model';
import { SharedSelectors } from '../../../../core/store/selectors/shared.selectors';
import { User } from '../../../../core/models/user.model';
import { takeUntil, take, switchMap, filter } from 'rxjs/operators';
import { ActivatedRoute } from '@angular/router';
import { isNullOrUndefined } from 'util';

@Component({
  selector: 'app-edit-delivery-address',
  templateUrl: './customer-edit-delivery-address.component.html',
  styleUrls: ['./customer-edit-delivery-address.component.scss'],
})
export class CustomerEditDeliveryAddressComponent implements OnInit, OnDestroy {
  @Select(SharedSelectors.getCustomerEditData) customerEditData$: Observable<EditCustomerData>;
  destroy$ = new Subject();
  customer: User;
  addressId: number;

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    this.route.params
      .pipe(
        switchMap((params) => {
          this.addressId = params['addressId'];
          return this.customerEditData$;
        }),
        filter((data) => !isNullOrUndefined(data)),
        take(1)
      )
      .subscribe((data: EditCustomerData) => {
        if (data && data.customer) {
          this.customer = data.customer;
        }
      });
  }

  ngOnDestroy() {
    this.destroy$.next();
  }
}
