import { ApplicationSettings } from '@nativescript/core';
import { Action, Selector, State, StateContext } from '@ngxs/store';
import { catchError, tap } from 'rxjs/operators';
import { APP_ID, wsEvaluation } 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 { EvaluationStateAll } from '../entities/input/allStates';
import { AllStatesOutput } from '../entities/output/allStatesOutput';
import { LoadStates } from './evaluation-states.actions';

export interface StatesStateModel {
    loadingStates: boolean;
    states: AllStatesOutput[];
}

const initialStateModel: StatesStateModel = {
    loadingStates: false,
    states: []
};

@State<StatesStateModel>({
    name: 'evaluationStates',
    defaults: initialStateModel
})

export class StatesState {

    @Selector()
    static getStates(state: StatesStateModel) {
        return state.states;
    }

    @Selector()
    static getStatesForProvider(state: StatesStateModel) {
        const states: PickerProvider[] = state.states
            .map(x => new PickerProvider(x.ID, x.DisplayName));

        return [new PickerProvider('', 'Nezáleží'), ...states];
    }

    @Selector()
    static isLoading(state: StatesStateModel) {
        return state.loadingStates;
    }

    constructor(
        private webApiService: WebApiService
    ) {}

    @Action(LoadStates)
    loadStates(ctx: StateContext<StatesStateModel>, action: LoadStates) {
        ctx.patchState({
            loadingStates: true
        });

        return this.webApiService.call(
            new EvaluationStateAll(APP_ID, ApplicationSettings.getString(USER_TOKEN)),
            () => new AllStatesOutput(),
            wsEvaluation
        ).pipe(
            tap((response: AllStatesOutput[]) => {
                ctx.patchState({
                    loadingStates: false,
                    states: response
                });
            }),
            catchError(e => {
                ctx.patchState({
                    loadingStates: false,
                    states: initialStateModel.states
                });
                throw e;
            })
        );
    }
}
