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 { PurchaseTypeAll } from '../entities/input/purchaseTypeAll';
import { WarehouseAll } from '../entities/input/warehouseAll';
import { WarehouseItemCategoryAll } from '../entities/input/warehouseItemCategoryAll';
import { WarehouseItemInsert } from '../entities/input/warehouseItemInsert';
import { PurchaseTypeAllOutput } from '../entities/output/purchaseTypeAllOutput';
import { WarehouseAllOutput } from '../entities/output/warehouseAllOutput';
import { WarehouseItemCategoryAllOutput } from '../entities/output/warehouseItemCategoryAllOutput';
import { WarehouseItemInsertOutput } from '../entities/output/warehouseItemInsertOutput';
import {
    CreateItemInsert,
    LoadPurchaseTypeAll,
    LoadWarehouseAll,
    LoadWarehouseItemCategoryAll
} from './material-new.action';

export interface MaterialNewStateModel {
    loadingWarehouses: boolean;
    loadingCategories: boolean;
    loadingPurchaseTypes: boolean;
    loadingItemInsert: boolean;
    warehouses: WarehouseAllOutput[];
    itemCategories: WarehouseItemCategoryAllOutput[];
    purchaseTypes: PurchaseTypeAllOutput[];
    itemInsert: WarehouseItemInsertOutput;
}

const initialStateModel: MaterialNewStateModel = {
    loadingWarehouses: false,
    loadingCategories: false,
    loadingPurchaseTypes: false,
    loadingItemInsert: false,
    warehouses: [],
    itemCategories: [],
    purchaseTypes: [],
    itemInsert: null
};

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

    @Selector()
    static getItemCategories(state: MaterialNewStateModel) {
        return state.itemCategories;
    }

    @Selector()
    static getPurchaseTypes(state: MaterialNewStateModel) {
        return state.purchaseTypes;
    }

    @Selector()
    static getItemInsert(state: MaterialNewStateModel) {
        return state.itemInsert;
    }

    @Selector()
    static isLoading(state: MaterialNewStateModel) {
        return state.loadingWarehouses
            || state.loadingCategories
            || state.loadingPurchaseTypes
            || state.loadingItemInsert;
    }

    constructor(
        private webApiService: WebApiService
    ) {
    }

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

                throw e;
            })
        );
    }

    /**
     * Load item categories
     *
     * @param {StateContext<MaterialNewStateModel>} ctx
     * @param {LoadWarehouseItemCategoryAll} action
     * @returns {Observable<any>}
     */
    @Action(LoadWarehouseItemCategoryAll)
    loadWarehouseItemCategoryAll(ctx: StateContext<MaterialNewStateModel>, action: LoadWarehouseItemCategoryAll) {
        ctx.patchState({
            loadingCategories: true
        });

        return this.webApiService.call(
            new WarehouseItemCategoryAll(APP_ID, ApplicationSettings.getString(USER_TOKEN)),
            () => new WarehouseItemCategoryAllOutput(),
            wsMaterial
        ).pipe(
            tap((response: WarehouseItemCategoryAllOutput[]) => {
                ctx.patchState({
                    loadingCategories: false,
                    itemCategories: response
                });
            }),
            catchError(e => {
                ctx.patchState({
                    loadingCategories: false,
                    itemCategories: initialStateModel.itemCategories
                });

                throw e;
            })
        );
    }

    /**
     * Load item purchase types
     *
     * @param {StateContext<MaterialNewStateModel>} ctx
     * @param {LoadPurchaseTypeAll} action
     * @returns {Observable<any>}
     */
    @Action(LoadPurchaseTypeAll)
    loadPurchaseTypeAll(ctx: StateContext<MaterialNewStateModel>, action: LoadPurchaseTypeAll) {
        ctx.patchState({
            loadingPurchaseTypes: true
        });

        return this.webApiService.call(
            new PurchaseTypeAll(APP_ID, ApplicationSettings.getString(USER_TOKEN)),
            () => new PurchaseTypeAllOutput(),
            wsMaterial
        ).pipe(
            tap((response: PurchaseTypeAllOutput[]) => {
                ctx.patchState({
                    loadingPurchaseTypes: false,
                    purchaseTypes: response
                });
            }),
            catchError(e => {
                ctx.patchState({
                    loadingPurchaseTypes: false,
                    purchaseTypes: initialStateModel.purchaseTypes
                });

                throw e;
            })
        );
    }

    /**
     * create item insert
     *
     * @param {StateContext<MaterialNewStateModel>} ctx
     * @param {CreateItemInsert} action
     * @returns {Observable<any>}
     */
    @Action(CreateItemInsert)
    createItemInsert(ctx: StateContext<MaterialNewStateModel>, action: CreateItemInsert) {
        ctx.patchState({
            loadingItemInsert: true
        });

        if (action.id) {
            return this.webApiService.call(
                new WarehouseItemInsert(APP_ID, ApplicationSettings.getString(USER_TOKEN),
                    action.id, action.displayName, action.idWarehouse, action.idCategory,
                    action.invNumber, action.description, action.purchDate, action.purchaseType,
                    action.purchaseNote, action.serNumber, action.accountNumber, action.purchasePrice, action.actualPrice,
                    action.eventRent, action.unitRent, action.commercialRent, action.rentPrice, action.rentNote,
                    action.note),
                () => new WarehouseItemInsertOutput(),
                wsMaterial
            ).pipe(
                tap((response: WarehouseItemInsertOutput[]) => {
                    ctx.patchState({
                        loadingItemInsert: false,
                        itemInsert: response[0]
                    });
                }),
                catchError(e => {
                    ctx.patchState({
                        loadingItemInsert: false,
                        itemInsert: initialStateModel.itemInsert
                    });

                    throw e;
                })
            );
        } else {
            ctx.patchState({
                loadingItemInsert: false,
                itemInsert: initialStateModel.itemInsert
            });
        }
    }
}
