import { Country } from '../../models/country.model';
import { State, Action, StateContext } from '@ngxs/store';
import { LoadCountries } from '../actions/countries.actions';
import { CustomerService } from '../../services/customer.service';
import { tap } from 'rxjs/operators';
import { Injectable } from '@angular/core';

export class CountryStateModel {
  countries: { [id: number]: Country };
}

@State<CountryStateModel>({
  name: 'countries',
  defaults: {
    countries: [],
  },
})
@Injectable()
export class CountryState {
  constructor(private customerService: CustomerService) {}

  @Action(LoadCountries)
  loadCountries(ctx: StateContext<CountryStateModel>, {}: LoadCountries) {
    return this.customerService.getCountries().pipe(
      tap((_countries: Country[]) => {
        const state = ctx.getState();
        const countries = { ...state.countries };

        _countries.forEach((country: Country) => {
          countries[country.id] = country;
        });

        ctx.patchState({ countries });
      })
    );
  }
}
