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 { WarehouseItemUpdateDelete } from '../entities/input/warehouseItemUpdateDelete';
import { WarehouseItemUpdateDeleteOutput } from '../entities/output/warehouseItemUpdateDeleteOutput';
import { CreateMaterialDelete } from './material-delete.action';

export interface MaterialDeleteStateModel {
    loadingMaterialDelete: boolean;
    materialDelete: WarehouseItemUpdateDeleteOutput;
}

const initialStateModel: MaterialDeleteStateModel = {
    loadingMaterialDelete: false,
    materialDelete: []
};

@State<MaterialDeleteStateModel>({
    name: 'materialDelete',
    defaults: initialStateModel
})
export class MaterialDeleteState {
    @Selector()
    static getItemDelete(state: MaterialDeleteStateModel) {
        return state.materialDelete;
    }

    @Selector()
    static isLoading(state: MaterialDeleteStateModel) {
        return state.loadingMaterialDelete;
    }

    constructor(
        private webApiService: WebApiService
    ) {
    }

    /**
     * create item delete
     *
     * @param {StateContext<MaterialDeleteStateModel>} ctx
     * @param {CreateMaterialDelete} action
     * @returns {Observable<any>}
     */
    @Action(CreateMaterialDelete)
    loadItemDelete(ctx: StateContext<MaterialDeleteStateModel>, action: CreateMaterialDelete) {
        ctx.patchState({
            loadingMaterialDelete: true
        });

        if (action.id) {
            return this.webApiService.call(
                new WarehouseItemUpdateDelete(APP_ID, ApplicationSettings.getString(USER_TOKEN), ApplicationSettings.getNumber(USER_UNIT_ID),
                    action.id, action.deletionDate, action.deletionNote),
                () => new WarehouseItemUpdateDeleteOutput(),
                wsMaterial
            ).pipe(
                tap((response: WarehouseItemUpdateDeleteOutput[]) => {
                    ctx.patchState({
                        loadingMaterialDelete: false,
                        materialDelete: response[0]
                    });
                }),
                catchError(e => {
                    ctx.patchState({
                        loadingMaterialDelete: false,
                        materialDelete: initialStateModel.materialDelete
                    });

                    throw e;
                })
            );
        } else {
            ctx.patchState({
                loadingMaterialDelete: false,
                materialDelete: initialStateModel.materialDelete
            });
        }
    }

}
