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 { EvaluationAllYear } from '../entities/input/allYears';
import { AllYearsOutput } from '../entities/output/allYearsOutput';
import { LoadYears } from './evaluation-years.actions';

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

const initialStateModel: YearsStateModel = {
    loadingYears: false,
    years: []
};

@State<YearsStateModel>({
    name: 'evaluationYears',
    defaults: initialStateModel
})

export class YearsState {

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

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

        return [new PickerProvider(0, 'Nezáleží'), ...years];
    }

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

    constructor(
        private webApiService: WebApiService
    ) {}

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

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