import { ApplicationSettings } from '@nativescript/core';
import { Action, Selector, State, StateContext } from '@ngxs/store';
import { catchError, tap } from 'rxjs/operators';
import { APP_ID, wsSummary } from '~/constants/api.constants';
import { USER_TOKEN } from '~/constants/login-constants';
import { WebApiService } from '~/core/services/web-api.service';
import { ExportPersonAll } from '../entities/input/exportPersonAll';
import { ExportPersonAllOutput } from '../entities/output/exportPersonAllOutput';
import { LoadExportPersonAll } from './export-new.actions';

export interface ExportNewStateModel {
    loadingExportPersonAll: boolean;
    exportPersonAll: ExportPersonAllOutput[];
}

const initialStateModel: ExportNewStateModel = {
    loadingExportPersonAll: false,
    exportPersonAll: []
};

@State<ExportNewStateModel>({
    name: 'exportNew',
    defaults: initialStateModel
})
export class ExportNewState {
    @Selector()
    static getExportPersonAll(state: ExportNewStateModel) {
        return state.exportPersonAll;
    }

    @Selector()
    static isLoading(state: ExportNewStateModel) {
        return state.loadingExportPersonAll;
    }

    constructor(
        private webApiService: WebApiService) {
    }

    /**
     * Load all export person templates
     *
     * @param {StateContext<ExportNewStateModel>} ctx
     * @param {LoadExportPersonAll} action
     * @returns {Observable<any>}
     */
    @Action(LoadExportPersonAll)
    loadExportPersonAll(ctx: StateContext<ExportNewStateModel>, action: LoadExportPersonAll) {
        ctx.patchState({
            loadingExportPersonAll: true
        });

        return this.webApiService.call(
            new ExportPersonAll(APP_ID, ApplicationSettings.getString(USER_TOKEN)),
            () => new ExportPersonAllOutput(),
            wsSummary
        ).pipe(
            tap((response: ExportPersonAllOutput[]) => {
                ctx.patchState({
                    loadingExportPersonAll: false,
                    exportPersonAll: response
                });
            }),
            catchError(e => {
                ctx.patchState({
                    loadingExportPersonAll: false,
                    exportPersonAll: initialStateModel.exportPersonAll
                });

                throw e;
            })
        );
    }
}
