import { Action, Selector, State, StateContext } from '@ngxs/store';
import { WebApiService } from '~/core/services/web-api.service';
import { ApplicationSettings as AppSettings } from '@nativescript/core';

import { USER_PERSON_ID, USER_TOKEN } from '~/constants/login-constants';
import { wsEvents } from '~/constants/api.constants';
import { catchError, tap } from 'rxjs/operators';
import { LoadEduEvents } from './edu-event-search.actions';
import {
    InsertEventEducationCourseEnrollment, InsertEventEducationCourseEnrollReminder, LoadEduEventQuestionAll, LoadEduEventReminderDetail,
    LoadEventEnrollDetail, UpdateEventEducationCourseEnrollment
} from './edu-event.actions';
import {
    EduEventCourseDetailEnrollOutput, EduEventEnrollReminderDetailOutput,
    EventQuestionAllOutput, EventEducationCourseEnrollReminderDetail,
    ParticipantEducationInsertEnroll, ParticipantEducationUpdateEnroll,
    EventEducationCourseEnrollReminderInsert, EventQuestionAll,
    EventEducationCourseDetailEnroll
} from '../../entities/edu-event.types';


export interface EduEventActionStateModel {
    enrollDetail: EduEventCourseDetailEnrollOutput;
    reminderDetail: EduEventEnrollReminderDetailOutput;
    enrollQuestions: EventQuestionAllOutput[],
}

const initialStateModel: EduEventActionStateModel = {
    enrollDetail: null,
    reminderDetail: null,
    enrollQuestions: [],
};


@State<EduEventActionStateModel>({
    name: 'eduEventActions',
    defaults: initialStateModel
})
export class EduEventActionState {

    constructor(
        private webApiService: WebApiService
    ) {
    }
    @Selector()
    static getEventLeaderDetail(state: EduEventActionStateModel) {
        return state.enrollDetail
    }
    @Selector()
    static getReminderDetail(state: EduEventActionStateModel) {
        return state.reminderDetail
    }
    @Selector()
    static getEnrollQuestions(state: EduEventActionStateModel) {
        return state.enrollQuestions
    }

    @Action(LoadEduEventReminderDetail)
    loadEventEducationCourseEnrollReminder(ctx: StateContext<EduEventActionStateModel>,
        action: LoadEduEventReminderDetail) {
        if (action.id !== 0) {
            const tk = AppSettings.getString(USER_TOKEN)
            return this.webApiService.call(
                new EventEducationCourseEnrollReminderDetail(
                    tk, action.id),
                () => new EduEventEnrollReminderDetailOutput(),
                wsEvents
            ).pipe(
                tap((response: EduEventEnrollReminderDetailOutput[]) => {
                    if (response.length === 1) {
                        ctx.patchState({
                            reminderDetail: response[0]
                        })
                    }
                }),
                catchError(e => {
                    ctx.patchState({
                        reminderDetail: initialStateModel.reminderDetail
                    });

                    throw e;
                })
            );
        } else {
            ctx.patchState({
                reminderDetail: initialStateModel.reminderDetail
            });
        }
    }

    @Action(InsertEventEducationCourseEnrollment)
    insertEventEducationCourseEnrollReminder(action: InsertEventEducationCourseEnrollment) {

        const tk = AppSettings.getString(USER_TOKEN)
        const p = AppSettings.getNumber(USER_PERSON_ID);
        const { phone, eventId: eventId, acknowledgement,
            affirmation, questions } = action.input
        if (action.input) {
            return this.webApiService.call(
                new ParticipantEducationInsertEnroll(
                    tk, eventId, p,
                    phone, acknowledgement, affirmation, questions),
                () => ({ ID: 0 }),
                wsEvents
            ).pipe(
                tap((res) => {
                    console.log(res)
                }),
                catchError(e => {
                    console.log(e)
                    throw e;
                })
            );
        }
    }

    @Action(UpdateEventEducationCourseEnrollment)
    updateEventEducationCourseEnrollReminder(action: UpdateEventEducationCourseEnrollment) {

        const tk = AppSettings.getString(USER_TOKEN)
        const p = AppSettings.getNumber(USER_PERSON_ID);
        const { phone, eventId: eventId, acknowledgement,
            affirmation, questions, verdictHealth } = action.input;
        // const formattedQuestions = this.getEnvelope(questions, '')
        if (action.input) {
            return this.webApiService.call(
                new ParticipantEducationUpdateEnroll(
                    tk, eventId, p,
                    phone, acknowledgement, affirmation, questions, verdictHealth),
                () => ({ ID: 0 }),
                wsEvents
            ).pipe(
                tap((res) => {
                    console.log(res)
                }),
                catchError(e => {
                    console.log(e)
                    throw e;
                })
            );
        }
    }

    @Action(InsertEventEducationCourseEnrollReminder)
    insertEventEducationCourseEnrollment(ctx: StateContext<EduEventActionStateModel>,
        action: InsertEventEducationCourseEnrollReminder) {
        const tk = AppSettings.getString(USER_TOKEN)
        const p = AppSettings.getNumber(USER_PERSON_ID);
        const { ID, ID_EventEducationCourse } = action.event
        if (action.event) {
            return this.webApiService.call(
                new EventEducationCourseEnrollReminderInsert(
                    tk, p,
                    ID, ID_EventEducationCourse, action.hours),
                () => ({ ID: 0 }),
                wsEvents
            ).pipe(
                tap(() => {
                    ctx.dispatch(new LoadEduEvents());
                }),
                catchError(e => {
                    ctx.patchState({
                        reminderDetail: initialStateModel.reminderDetail
                    });

                    throw e;
                })
            );
        }
    }

    @Action(LoadEduEventQuestionAll)
    loadEduEventQuestions(ctx: StateContext<EduEventActionStateModel>,
        action: LoadEduEventQuestionAll) {

        const tk = AppSettings.getString(USER_TOKEN)
        if (action.eventId) {
            return this.webApiService.call(
                new EventQuestionAll(
                    tk, action.eventId, action.eventCourseId, action.participantId),
                () => new EventQuestionAllOutput(),
                wsEvents
            ).pipe(
                tap((res: EventQuestionAllOutput[]) => {
                    ctx.patchState({
                        enrollQuestions: res
                    });

                }),
                catchError(e => {
                    ctx.patchState({
                        enrollQuestions: initialStateModel.enrollQuestions
                    });

                    throw e;
                })
            );
        }
    }

    @Action(LoadEventEnrollDetail)
    loadEventEnrollDetail(ctx: StateContext<EduEventActionStateModel>,
        action: LoadEventEnrollDetail) {

        if (action.courseId) {
            return this.webApiService.call(
                new EventEducationCourseDetailEnroll(
                    AppSettings.getString(USER_TOKEN),
                    action.courseId, action.personId),
                () => new EduEventCourseDetailEnrollOutput(),
                wsEvents
            ).pipe(
                tap((response: EduEventCourseDetailEnrollOutput[]) => {
                    if (response.length === 1) {
                        ctx.patchState({
                            enrollDetail: response[0]
                        });
                    }

                }),
                catchError(e => {
                    ctx.patchState({
                        enrollDetail: initialStateModel.enrollDetail
                    });

                    throw e;
                })
            );
        }
    }



}