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, USER_UNIT_ID } from '~/constants/login-constants';
import { WebApiService } from '~/core/services/web-api.service';
import { MembershipApplicationInsert } from '../entities/input/membershipApplicationInsert';
import { MembershipApplicationInsertOutput } from '../entities/output/membershipApplicationInsertOutput';
import { CreateApplicationInsert } from './application.actions';

export interface ApplicationNewStateModel {
    applicationInsert: MembershipApplicationInsertOutput;
}

const initialStateModel: ApplicationNewStateModel = {
    applicationInsert: null
};

@State<ApplicationNewStateModel>({
    name: 'application',
    defaults: initialStateModel
})

export class ApplicationNewState {

    @Selector()
    static getApplicationInsert(state: ApplicationNewStateModel) {
        return state.applicationInsert;
    }

    constructor(
        private webApiService: WebApiService
    ) {}

    /**
     * create application insert
     *
     * @param {StateContext<ApplicationNewStateModel>} ctx
     * @param {CreateApplicationInsert} action
     * @returns {Observable<any>}
     */
    @Action(CreateApplicationInsert)
    createApplicationInsert(ctx: StateContext<ApplicationNewStateModel>, action: CreateApplicationInsert) {

        const applicationNewInsert = new MembershipApplicationInsert(
            APP_ID,
            ApplicationSettings.getString(USER_TOKEN),
            ApplicationSettings.getNumber(USER_UNIT_ID),
            action.id,
            action.firstName,
            action.secondName,
            !action.isChild,
            action.firstNameParent,
            action.secondNameParent,
            action.email
        );

        return this.webApiService.call(
            applicationNewInsert,
            () => new MembershipApplicationInsertOutput(),
            wsOrganizationUnit
        ).pipe(
            tap((response: MembershipApplicationInsertOutput[]) => {
                ctx.patchState({
                    applicationInsert: response[0]
                });
            }),
            catchError(e => {
                ctx.patchState({
                    applicationInsert: initialStateModel.applicationInsert
                });
                console.log(applicationNewInsert);
                throw e;
            })
        );
    }
}
