import { ApplicationSettings } from '@nativescript/core';
import { Action, Selector, State, StateContext } from '@ngxs/store';
import { catchError, tap } from 'rxjs/operators';
import { APP_ID, wsOrganizationUnit } from '~/constants/api.constants';
import { USER_TOKEN } from '~/constants/login-constants';
import { WebApiService } from '~/core/services/web-api.service';
import { FunctionAll } from '~/pages/unit/entities/input/functionAll';
import { FunctionAllOutput } from '~/pages/unit/entities/output/functionAllOutput';
import { LoadUnitFunctions } from '~/pages/unit/state-mgmt/unit-functions.actions';

export interface UnitFunctionsStateModel {
    loadingUnitFunctions: boolean;
    unitFunctions: FunctionAllOutput[];
}

const initialStateModel: UnitFunctionsStateModel = {
    loadingUnitFunctions: false,
    unitFunctions: []
};

@State<UnitFunctionsStateModel>({
    name: 'unitFunctions',
    defaults: initialStateModel
})

export class UnitFunctionsState {

    @Selector()
    static getUnitFunctions(state: UnitFunctionsStateModel) {
        return state.unitFunctions;
    }

    @Selector()
    static isLoading(state: UnitFunctionsStateModel) {
        return state.loadingUnitFunctions;
    }

    constructor(
        private webApiService: WebApiService
    ) {
    }

    @Action(LoadUnitFunctions)
    loadUnitFunctions(ctx: StateContext<UnitFunctionsStateModel>, action: LoadUnitFunctions) {
        ctx.patchState({
            loadingUnitFunctions: true
        });

        if (action.unitId) {
            return this.webApiService.call(
                new FunctionAll(APP_ID, ApplicationSettings.getString(USER_TOKEN), action.unitId),
                () => new FunctionAllOutput(),
                wsOrganizationUnit
            ).pipe(
                tap((response: FunctionAllOutput[]) => {
                    ctx.patchState({
                        loadingUnitFunctions: false,
                        unitFunctions: response
                    });
                }),
                catchError(e => {
                    ctx.patchState({
                        loadingUnitFunctions: false,
                        unitFunctions: initialStateModel.unitFunctions
                    });

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