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 { BaseOutput } from '~/core/entities/output/baseOutput';
import { WebApiService } from '~/core/services/web-api.service';
import { EvaluationAnswerPerson, EvaluationPersonUpdate } from '../entities/input/personUpdate';
import { UpdateIndivEvaluation } from './evaluation-person-update.actions';

export interface UpdateIndivEvaluationStateModel {
    loadingUpdate: boolean;
    answers: EvaluationAnswerPerson[];
    ID: number;
    error: string;
}

const initialStateModel: UpdateIndivEvaluationStateModel = {
    loadingUpdate: false,
    answers: null,
    ID: 0,
    error: ''
};

@State<UpdateIndivEvaluationStateModel>({
    name: 'updatePersonEval',
    defaults: initialStateModel
})

export class UpdateIndivEvaluationState {

    @Selector()
    static isLoading(state: UpdateIndivEvaluationStateModel) {
        return state.loadingUpdate;
    }

    @Selector()
    static getError(state: UpdateIndivEvaluationStateModel) {
        return state.error;
    }

    constructor(
        private webApiService: WebApiService
    ) {}

    @Action(UpdateIndivEvaluation)
    loadEvaluations(ctx: StateContext<UpdateIndivEvaluationStateModel>, action: UpdateIndivEvaluation) {
        ctx.patchState({
            loadingUpdate: true,
            answers: action.answers,
            ID: action.id
        });

        return this.webApiService.call(
            new EvaluationPersonUpdate(APP_ID, ApplicationSettings.getString(USER_TOKEN), ctx.getState().ID, ctx.getState().answers),
            () => new BaseOutput(),
            wsEvaluation
        ).pipe(
            tap((response: BaseOutput) => {
                ctx.patchState({
                    loadingUpdate: false,
                    error: ''
                });
            }),
            catchError(e => {
                ctx.patchState({
                    loadingUpdate: false,
                    error: e.error
                });
                throw e;
            })
        );
    }
}
