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 { MembershipAll } from '~/pages/unit/entities/input/membershipAll';
import { MembershipAllOutput } from '~/pages/unit/entities/output/membershipAllOutput';
import { LoadUnitMemberships } from '~/pages/unit/state-mgmt/unit-memberships.actions';

export interface UnitMembershipsStateModel {
    loadingUnitMembership: boolean;
    unitMemberships: MembershipAllOutput[];
}

const initialStateModel: UnitMembershipsStateModel = {
    loadingUnitMembership: false,
    unitMemberships: []
};

@State<UnitMembershipsStateModel>({
    name: 'unitMemberships',
    defaults: initialStateModel
})

export class UnitMembershipsState {

    @Selector()
    static getUnitMemberships(state: UnitMembershipsStateModel) {
        return state.unitMemberships;
    }

    @Selector()
    static isLoading(state: UnitMembershipsStateModel) {
        return state.loadingUnitMembership;
    }

    constructor(
        private webApiService: WebApiService
    ) {
    }

    @Action(LoadUnitMemberships)
    loadUnitMemberships(ctx: StateContext<UnitMembershipsStateModel>, action: LoadUnitMemberships) {
        ctx.patchState({
            loadingUnitMembership: true
        });

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

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