import { ApplicationSettings } from '@nativescript/core';
import { Action, Selector, State, StateContext } from '@ngxs/store';
import { catchError, tap } from 'rxjs/operators';
import { APP_ID, wsOrganizationUnit } from '~/constants/api.constants';
import { USER_TOKEN } from '~/constants/login-constants';
import { PickerProvider } from '~/core/entities/picker-provider';
import { WebApiService } from '~/core/services/web-api.service';
import { OfferTypeAll } from '~/pages/search-person/entities/input/offerTypeAll';
import { OfferTypeAllOutput } from '~/pages/search-person/entities/output/offerTypeAllOutput';
import { LoadOfferTypes } from '~/pages/search-person/state-mgmt/search-person.actions';

export interface SearchPersonStateModel {
    loadingOfferTypes: boolean;
    offerTypes: OfferTypeAllOutput[];
}

const initialStateModel: SearchPersonStateModel = {
    loadingOfferTypes: false,
    offerTypes: []
};

@State<SearchPersonStateModel>({
    name: 'searchPerson',
    defaults: initialStateModel
})

export class SearchPersonState {

    @Selector()
    static getOfferTypes(state: SearchPersonStateModel) {
        return state.offerTypes;
    }

    @Selector()
    static getOfferTypesForProvider(state: SearchPersonStateModel) {
        const offerTypes: PickerProvider[] = state.offerTypes
            .map(offerType => new PickerProvider(offerType.ID, offerType.DisplayName));

        return [new PickerProvider(0, 'Všechny'), ...offerTypes];
    }

    @Selector()
    static isLoading(state: SearchPersonStateModel) {
        return state.loadingOfferTypes;
    }

    constructor(
        private webApiService: WebApiService
    ) {
    }

    @Action(LoadOfferTypes)
    loadOfferTypes(ctx: StateContext<SearchPersonStateModel>, action: LoadOfferTypes) {
        ctx.patchState({
            loadingOfferTypes: true
        });

        return this.webApiService.call(
            new OfferTypeAll(APP_ID, ApplicationSettings.getString(USER_TOKEN)),
            () => new OfferTypeAllOutput(),
            wsOrganizationUnit
        ).pipe(
            tap((response: OfferTypeAllOutput[]) => {
                ctx.patchState({
                    loadingOfferTypes: false,
                    offerTypes: response
                });
            }),
            catchError(e => {
                ctx.patchState({
                    loadingOfferTypes: false,
                    offerTypes: initialStateModel.offerTypes
                });

                throw e;
            })
        );
    }

}
