import { ApplicationSettings } from '@nativescript/core';
import { Action, Selector, State, StateContext } from '@ngxs/store';
import { catchError, tap } from 'rxjs/operators';
import { APP_ID, wsMessage } from '~/constants/api.constants';
import { USER_TOKEN } from '~/constants/login-constants';
import { WebApiService } from '~/core/services/web-api.service';
import { MessageAllWeb } from '~/pages/message/entities/input/messageAllWeb';
import { MessageAllWebOutput } from '~/pages/message/entities/output/messageAllWebOutput';
import { LoadMessageAllWeb } from '~/pages/message/state-mgmt/message.actions';

export interface MessageStateModel {
    loadingMessageAllWeb: boolean;
    messageAllWeb: MessageAllWebOutput[];
}

const initialStateModel: MessageStateModel = {
    loadingMessageAllWeb: false,
    messageAllWeb: []
};

@State<MessageStateModel>({
    name: 'message',
    defaults: initialStateModel
})

export class MessageState {

    @Selector()
    static getMessageAllWeb(state: MessageStateModel) {
        return state.messageAllWeb;
    }

    @Selector()
    static isLoading(state: MessageStateModel) {
        return state.loadingMessageAllWeb;
    }

    constructor(
        private webApiService: WebApiService
    ) {
    }

    /**
     * Load messages
     *
     * @param {StateContext<StsStateModel>} ctx
     * @param {LoadEnrollNumbers} action
     * @returns {Observable<any>}
     */
    @Action(LoadMessageAllWeb)
    loadMessageAllWeb(ctx: StateContext<MessageStateModel>, action: LoadMessageAllWeb) {
        ctx.patchState({
            loadingMessageAllWeb: true
        });

        return this.webApiService.call(
            new MessageAllWeb(APP_ID, ApplicationSettings.getString(USER_TOKEN)),
            () => new MessageAllWebOutput(),
            wsMessage
        ).pipe(
            tap((response: MessageAllWebOutput[]) => {
                ctx.patchState({
                    loadingMessageAllWeb: false,
                    messageAllWeb: response
                });
            }),
            catchError(e => {
                ctx.patchState({
                    loadingMessageAllWeb: false,
                    messageAllWeb: initialStateModel.messageAllWeb
                });

                throw e;
            })
        );
    }
}
