import { Component, OnInit } from '@angular/core';
import { Select, Store } from '@ngxs/store';
import { ModalDialogParams, RouterExtensions } from '@nativescript/angular';
import { FeedbackType } from 'nativescript-feedback';
import { Observable } from 'rxjs';
import { EduEventEnrollReminderDetailOutput } from '~/pages/event/entities/edu-event.types';
import { EduEventOutput } from '~/pages/event/entities/edu-event-search.types';
import { EduEventActionState } from '~/pages/event/state-mgmt/edu/edu-event-action.state';
import { LoadEduEventReminderDetail, InsertEventEducationCourseEnrollReminder } from '~/pages/event/state-mgmt/edu/edu-event.actions';
import { feedbackMessage } from '~/pages/material/utils/feedback-messages';


@Component({
    selector: 'EduEventCourseEnrollReminderPageComponent',
    moduleId: module.id,
    templateUrl: './edu-event-course-enroll-reminder-page.component.html',
    styleUrls: ['./_edu-event-course-enroll-reminder-page.component.scss'],
})
export class EduEventCourseEnrollReminderPageComponent implements OnInit {

    @Select(EduEventActionState.getReminderDetail)
    reminderDetail$: Observable<EduEventEnrollReminderDetailOutput>;

    hourForm = { value: '24' }

    reminderDetail: EduEventEnrollReminderDetailOutput;
    event: EduEventOutput
    reminderId: number = 0;
    constructor(
        private routerExtensions: RouterExtensions,
        private params: ModalDialogParams,
        private store: Store,

    ) {
    }
    ngOnInit(): void {
        this.event = this.params.context.event;
        this.reminderId = this.event.ID_EventEducationCourseEnrollReminder;
        this.hourForm = { value: '24' }
        if (this.reminderId) {
            this.store.dispatch([new LoadEduEventReminderDetail(this.reminderId)])
        } else {
            this.store.dispatch([new LoadEduEventReminderDetail(0)])
        }
        this.reminderDetail$.subscribe(res => {
            this.reminderDetail = res;
            if (res) {
                this.hourForm = { value: res.Hours.toString() }
            }
        })

    }

    onBackButton(): void {
        this.routerExtensions.back();
    }

    close() {
        this.params.closeCallback();
    }

    submit() {
        const hours = parseInt(this.hourForm.value, 10)
        if (!this.event.ID_EventEducationCourseEnrollReminder) {
            this.store.dispatch(new InsertEventEducationCourseEnrollReminder(this.event, hours))
                .subscribe((res) => {
                    feedbackMessage(FeedbackType.Success, "Nastavení upozornění", `Upozornění zapnuto.`);
                    this.params.closeCallback();

                }, err => {
                    console.log(err);
                    feedbackMessage(FeedbackType.Error, "Nastavení upozornění", `Pri nastavení upozornění došlo k chybě. Zkuste ještě jednou.`);
                });
        }

    }


}