import { ApplicationSettings } from '@nativescript/core';
import { Action, Selector, State, StateContext } from '@ngxs/store';
import { catchError, tap } from 'rxjs/operators';
import { APP_ID, wsEvaluation } from '~/constants/api.constants';
import { USER_TOKEN } from '~/constants/login-constants';
import { PickerProvider } from '~/core/entities/picker-provider';
import { WebApiService } from '~/core/services/web-api.service';
import { EvaluationAllYearCreate } from '../entities/input/allYearsCreate';
import { AllYearsOutput } from '../entities/output/allYearsOutput';
import { LoadYearsCreate } from './evaluation-years-create.actions';

export interface YearsCreateStateModel {
    loadingYears: boolean;
    years: AllYearsOutput[];
    IsUnit: boolean;
}

const initialStateModel: YearsCreateStateModel = {
    loadingYears: false,
    years: [],
    IsUnit: true
};

@State<YearsCreateStateModel>({
    name: 'evaluationYearsCreate',
    defaults: initialStateModel
})

export class YearsCreateState {

    @Selector()
    static getYears(state: YearsCreateStateModel) {
        return state.years;
    }

    @Selector()
    static getYearsForProvider(state: YearsCreateStateModel) {
        const years: PickerProvider[] = state.years
            .map(x => new PickerProvider(x.Year, x.Year.toString()));

        return years;
    }

    @Selector()
    static isLoading(state: YearsCreateStateModel) {
        return state.loadingYears;
    }

    constructor(
        private webApiService: WebApiService
    ) {}

    @Action(LoadYearsCreate)
    loadYears(ctx: StateContext<YearsCreateStateModel>, action: LoadYearsCreate) {
        ctx.patchState({
            loadingYears: true
        });

        return this.webApiService.call(
            new EvaluationAllYearCreate(APP_ID, ApplicationSettings.getString(USER_TOKEN), ctx.getState().IsUnit),
            () => new AllYearsOutput(),
            wsEvaluation
        ).pipe(
            tap((response: AllYearsOutput[]) => {
                ctx.patchState({
                    loadingYears: false,
                    years: response
                });
            }),
            catchError(e => {
                ctx.patchState({
                    loadingYears: false,
                    years: initialStateModel.years
                });
                throw e;
            })
        );
    }
}
