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 { WarehouseDetail } from '../entities/input/warehouseDetail';
import { WarehouseItemAll } from '../entities/input/warehouseItemAll';
import { WarehouseDetailOutput } from '../entities/output/warehouseDetailOutput';
import { WarehouseItemAllOutput } from '../entities/output/warehouseItemAllOutput';
import { LoadWarehouseDetail, LoadWarehouseItemAll } from './warehouse-detail.action';

export interface WarehouseDetailStateModel {
    loadingWarehouseDetail: boolean;
    loadingWarehouseItems: boolean;
    warehouseDetail: WarehouseDetailOutput;
    warehouseItems: WarehouseItemAllOutput[];
}

const initialStateModel: WarehouseDetailStateModel = {
    loadingWarehouseDetail: false,
    loadingWarehouseItems: false,
    warehouseDetail: null,
    warehouseItems: null
};

@State<WarehouseDetailStateModel>({
    name: 'warehouseDetail',
    defaults: initialStateModel
})
export class WarehouseDetailState {
    @Selector()
    static getWarehouseDetail(state: WarehouseDetailStateModel) {
        return state.warehouseDetail;
    }

    @Selector()
    static getWarehouseItems(state: WarehouseDetailStateModel) {
        return state.warehouseItems;
    }

    @Selector()
    static isLoading(state: WarehouseDetailStateModel) {
        return state.loadingWarehouseDetail || state.loadingWarehouseItems;
    }

    constructor(
        private webApiService: WebApiService
    ) {
    }

    /**
     * Load warehouse detail
     *
     * @param {StateContext<WarehouseDetailStateModel>} ctx
     * @param {LoadWarehouseDetail} action
     * @returns {Observable<any>}
     */
    @Action(LoadWarehouseDetail)
    loadWarehouseDetail(ctx: StateContext<WarehouseDetailStateModel>, action: LoadWarehouseDetail) {
        ctx.patchState({
            loadingWarehouseDetail: true
        });

        if (action.id) {
            return this.webApiService.call(
                new WarehouseDetail(APP_ID, ApplicationSettings.getString(USER_TOKEN), action.id),
                () => new WarehouseDetailOutput(),
                wsMaterial
            ).pipe(
                tap((response: WarehouseDetailOutput[]) => {
                    if (response.length === 1) {

                        ctx.patchState({
                            loadingWarehouseDetail: false,
                            warehouseDetail: response[0]
                        });
                    } else {
                        ctx.patchState({
                            loadingWarehouseDetail: false,
                            warehouseDetail: initialStateModel.warehouseDetail
                        });
                        throw new Error('Nepodařilo se nalézt detail skladu');
                    }
                }),
                catchError(e => {
                    ctx.patchState({
                        loadingWarehouseDetail: false,
                        warehouseDetail: initialStateModel.warehouseDetail
                    });

                    throw e;
                })
            );
        } else {
            ctx.patchState({
                loadingWarehouseDetail: false
            });
        }
    }

    /**
     * Load warehouses items
     *
     * @param {StateContext<WarehouseDetailStateModel>} ctx
     * @param {LoadWarehouseItemAll} action
     * @returns {Observable<any>}
     */
    @Action(LoadWarehouseItemAll)
    loadWarehouseItems(ctx: StateContext<WarehouseDetailStateModel>, action: LoadWarehouseItemAll) {
        ctx.patchState({
            loadingWarehouseItems: true
        });

        return this.webApiService.call(
            new WarehouseItemAll(APP_ID, ApplicationSettings.getString(USER_TOKEN), ApplicationSettings.getNumber(USER_UNIT_ID), false, action.idWarehouses),
            () => new WarehouseItemAllOutput(),
            wsMaterial
        ).pipe(
            tap((response: WarehouseItemAllOutput[]) => {
                ctx.patchState({
                    loadingWarehouseItems: false,
                    warehouseItems: response
                });
            }),
            catchError(e => {
                ctx.patchState({
                    loadingWarehouseItems: false,
                    warehouseItems: initialStateModel.warehouseItems
                });

                throw e;
            })
        );
    }

}
