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 { WebApiService } from '~/core/services/web-api.service';
import { EvaluationSubtypeAll } from '../entities/input/allEvalSubtypes';
import { AllSubtypesOutput } from '../entities/output/allEvalSubtypesOutput';
import { LoadEvalSubtypes } from './evaluation-all-eval-subtypes.actions';

export interface EvaluationSubtypesStateModel {
    loadingSubtypes: boolean;
    subtypes: AllSubtypesOutput[];
}

const initialStateModel: EvaluationSubtypesStateModel = {
    loadingSubtypes: false,
    subtypes: []
};

@State<EvaluationSubtypesStateModel>({
    name: 'evaluationSubtypes',
    defaults: initialStateModel
})

export class EvaluationSubtypesState {

    @Selector()
    static getSubtypes(state: EvaluationSubtypesStateModel) {
        return state.subtypes;
    }

    @Selector()
    static isLoading(state: EvaluationSubtypesStateModel) {
        return state.loadingSubtypes;
    }

    constructor(
        private webApiService: WebApiService
    ) {}

    @Action(LoadEvalSubtypes)
    loadYears(ctx: StateContext<EvaluationSubtypesStateModel>, action: LoadEvalSubtypes) {
        ctx.patchState({
            loadingSubtypes: true
        });

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