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_PERSON_ID, USER_TOKEN } from '~/constants/login-constants';
import { WebApiService } from '~/core/services/web-api.service';
import { EvaluationPersonAllEvaluation } from '../entities/input/individualEvaluation';
import { EvaluationPersonAllEvaluationOutput } from '../entities/output/individualEvaluationsOutput';
import { LoadIndivEvaluations, SetIDEvaluation } from './evaluation-person-all.actions';

export interface SearchEvaluationPersonAllStateModel {
    loadingEvaluations: boolean;
    indivEvaluations: EvaluationPersonAllEvaluationOutput[];
    ID_Evaluation: number;
}

const initialStateModel: SearchEvaluationPersonAllStateModel = {
    loadingEvaluations: false,
    indivEvaluations: [],
    ID_Evaluation: 0
};

@State<SearchEvaluationPersonAllStateModel>({
    name: 'evaluationPersonAll',
    defaults: initialStateModel
})

export class SearchEvaluationPersonAllState {

    @Selector()
    static isLoading(state: SearchEvaluationPersonAllStateModel) {
        return state.loadingEvaluations;
    }

    @Selector()
    static getIndivEvaluations(state: SearchEvaluationPersonAllStateModel) {
        return state.indivEvaluations;
    }

    constructor(
        private webApiService: WebApiService
    ) {}

    @Action(SetIDEvaluation)
    setSearchEvaluationParams(ctx: StateContext<SearchEvaluationPersonAllStateModel>, action: SetIDEvaluation) {
        ctx.patchState({
            ID_Evaluation: action.evaluationId
        });
    }

    @Action(LoadIndivEvaluations)
    loadEvaluations(ctx: StateContext<SearchEvaluationPersonAllStateModel>, action: LoadIndivEvaluations) {
        ctx.patchState({
            loadingEvaluations: true
        });

        return this.webApiService.call(
            new EvaluationPersonAllEvaluation(APP_ID, ApplicationSettings.getString(USER_TOKEN), ctx.getState().ID_Evaluation, ApplicationSettings.getNumber(USER_PERSON_ID)),
            () => new EvaluationPersonAllEvaluationOutput(),
            wsEvaluation
        ).pipe(
            tap((response: EvaluationPersonAllEvaluationOutput[]) => {
                ctx.patchState({
                    loadingEvaluations: false,
                    indivEvaluations: response
                });
            }),
            catchError(e => {
                ctx.patchState({
                    loadingEvaluations: false,
                    indivEvaluations: initialStateModel.indivEvaluations
                });
                throw e;
            })
        );
    }
}
