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

export interface AnswersStateModel {
    loadingAnswers: boolean;
    answers: EvaluationAnswerAllOutput[];
    ID_Evaluation: number;
}

const initialStateModel: AnswersStateModel = {
    loadingAnswers: false,
    answers: null,
    ID_Evaluation: 0
};

@State<AnswersStateModel>({
    name: 'answers',
    defaults: initialStateModel
})

export class AnswersState {

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

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

    @Selector()
    static getIDEval(state: AnswersStateModel) {
        return state.ID_Evaluation;
    }

    constructor(
        private webApiService: WebApiService
    ) {}

    @Action(LoadAnswers)
    loadEvaluations(ctx: StateContext<AnswersStateModel>, action: LoadAnswers) {
        ctx.patchState({
            loadingAnswers: true,
            ID_Evaluation: action.evaluationId
        });

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