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 { WarehouseItemAllBorrowable } from '../entities/input/warehouseItemAllBorrowable';
import { WarehouseAllOutput } from '../entities/output/warehouseAllOutput';
import { WarehouseItemAllBorrowableOutput } from '../entities/output/warehouseItemAllBorrowableOutput';
import { LoadBorrowableItems, LoadWarehouseAll } from './reservation.action';

export interface ReservationStateModel {
    loadingWarehouseItemAllBorrowable: boolean;
    loadingWarehouseAll: boolean;
    warehouseBorrowableItem: WarehouseItemAllBorrowableOutput[];
    warehouseAll: WarehouseAllOutput[];
}

const initialStateModel: ReservationStateModel = {
    loadingWarehouseItemAllBorrowable: false,
    loadingWarehouseAll: false,
    warehouseBorrowableItem: [],
    warehouseAll: []
};

@State<ReservationStateModel>({
    name: 'reservation',
    defaults: initialStateModel
})
export class ReservationState {
    @Selector()
    static getWarehouseBorrowableItems(state: ReservationStateModel) {
        return state.warehouseBorrowableItem;
    }

    @Selector()
    static getWarehouseAll(state: ReservationStateModel) {
        return state.warehouseAll;
    }

    @Selector()
    static isLoading(state: ReservationStateModel) {
        return state.loadingWarehouseItemAllBorrowable
            || state.loadingWarehouseAll;
    }

    constructor(
        private webApiService: WebApiService
    ) { }

    /**
     * Load all borrowable items
     *
     * @param {StateContext<ReservationStateModel>} ctx
     * @param {LoadBorrowableItems} action
     * @returns {Observable<any>}
     */
    @Action(LoadBorrowableItems)
    loadBorrowableItemsAll(ctx: StateContext<ReservationStateModel>, action: LoadBorrowableItems) {
        ctx.patchState({
            loadingWarehouseItemAllBorrowable: true
        });

        return this.webApiService.call(
            new WarehouseItemAllBorrowable(APP_ID, ApplicationSettings.getString(USER_TOKEN), false, true),
            () => new WarehouseItemAllBorrowableOutput(),
            wsMaterial
        ).pipe(
            tap((response: WarehouseItemAllBorrowableOutput[]) => {
                ctx.patchState({
                    loadingWarehouseItemAllBorrowable: false,
                    warehouseBorrowableItem: response
                });
            }),
            catchError(e => {
                ctx.patchState({
                    loadingWarehouseItemAllBorrowable: false,
                    warehouseBorrowableItem: initialStateModel.warehouseBorrowableItem
                });

                throw e;
            })
        );
    }

    /**
     * Load warehouses
     *
     * @param {StateContext<ReservationStateModel>} ctx
     * @param {LoadWarehouseAll} action
     * @returns {Observable<any>}
     */
    @Action(LoadWarehouseAll)
    loadWarehouseAll(ctx: StateContext<ReservationStateModel>, 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,
                    warehouseAll: response
                });
            }),
            catchError(e => {
                ctx.patchState({
                    loadingWarehouseAll: false,
                    warehouseAll: initialStateModel.warehouseAll
                });

                throw e;
            })
        );
    }
}
