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 { EvaluationAnswerAllEvaluationPerson } from '../entities/input/evaluationAnswers';
import { EvaluationAnswerAllOutput } from '../entities/output/evaluationAnswersOutput';
import { LoadAnswersIndividual } from './evaluation-answers-individual.actions';

export interface AnswersIndividualStateModel {
    loadingAnswers: boolean;
    answers: EvaluationAnswerAllOutput[];
    ID_EvaluationPerson: number;
}

const initialStateModel: AnswersIndividualStateModel = {
    loadingAnswers: false,
    answers: null,
    ID_EvaluationPerson: 0
};

@State<AnswersIndividualStateModel>({
    name: 'answersIndividual',
    defaults: initialStateModel
})

export class AnswersIndividualState {

    @Selector()
    static isLoading(state: AnswersIndividualStateModel) {
        return state.loadingAnswers;
    }

    @Selector()
    static getAnswers(state: AnswersIndividualStateModel) {
        return state.answers;
    }

    @Selector()
    static getIDEvalPerson(state: AnswersIndividualStateModel) {
        return state.ID_EvaluationPerson;
    }

    constructor(
        private webApiService: WebApiService
    ) {}

    @Action(LoadAnswersIndividual)
    loadEvaluations(ctx: StateContext<AnswersIndividualStateModel>, action: LoadAnswersIndividual) {
        ctx.patchState({
            loadingAnswers: true,
            ID_EvaluationPerson: action.evaluationPersonId
        });

        return this.webApiService.call(
            new EvaluationAnswerAllEvaluationPerson(APP_ID, ApplicationSettings.getString(USER_TOKEN), ctx.getState().ID_EvaluationPerson),
            () => new EvaluationAnswerAllOutput(),
            wsEvaluation
        ).pipe(
            tap((response: EvaluationAnswerAllOutput[]) => {
                ctx.patchState({
                    loadingAnswers: false,
                    answers: response
                });
            }),
            catchError(e => {
                ctx.patchState({
                    loadingAnswers: false,
                    answers: initialStateModel.answers
                });
                throw e;
            })
        );
    }
}
