import { ApplicationSettings } from '@nativescript/core';
import { Action, Selector, State, StateContext } from '@ngxs/store';
import { catchError, tap } from 'rxjs/operators';
import { APP_ID, wsMaterial } from '~/constants/api.constants';
import { USER_TOKEN, USER_UNIT_ID } from '~/constants/login-constants';
import { WebApiService } from '~/core/services/web-api.service';
import { WarehouseAll } from '../entities/input/warehouseAll';
import { WarehouseAllOutput } from '../entities/output/warehouseAllOutput';
import { LoadWarehouseAll } from './warehouse-unit.actions';

export interface WarehouseUnitStateModel {
    loadingWarehouseAll: boolean;
    warehouses: WarehouseAllOutput[];
}

const initialStateModel: WarehouseUnitStateModel = {
    loadingWarehouseAll: false,
    warehouses: []
};

@State<WarehouseUnitStateModel>({
    name: 'warehouseUnit',
    defaults: initialStateModel
})
export class WarehouseUnitState {
    @Selector()
    static getWarehouses(state: WarehouseUnitStateModel) {
        return state.warehouses;
    }

    @Selector()
    static isLoading(state: WarehouseUnitStateModel) {
        return state.loadingWarehouseAll;
    }

    constructor(
        private webApiService: WebApiService
    ) {
    }

    /**
     * Load warehouses
     *
     * @param {StateContext<WarehouseUnitStateModel>} ctx
     * @param {LoadWarehouseAll} action
     * @returns {Observable<any>}
     */
    @Action(LoadWarehouseAll)
    loadWarehouseAll(ctx: StateContext<WarehouseUnitStateModel>, action: LoadWarehouseAll) {
        ctx.patchState({
            loadingWarehouseAll: true
        });

        return this.webApiService.call(
            new WarehouseAll(APP_ID, ApplicationSettings.getString(USER_TOKEN), ApplicationSettings.getNumber(USER_UNIT_ID)),
            () => new WarehouseAllOutput(),
            wsMaterial
        ).pipe(
            tap((response: WarehouseAllOutput[]) => {
                ctx.patchState({
                    loadingWarehouseAll: false,
                    warehouses: response
                });
            }),
            catchError(e => {
                ctx.patchState({
                    loadingWarehouseAll: false,
                    warehouses: initialStateModel.warehouses
                });

                throw e;
            })
        );
    }

}
