import { Component, Input } from '@angular/core';
import { ActionsExecuting } from '@ngxs-labs/actions-executing';
import { Select, Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { EduEventDetailState } from '~/pages/event/state-mgmt/edu/edu-event-detail.state';
import { EduEventCourseOutput } from '~/pages/event/entities/edu-event-detail.types';
import { LoadEduEventCourses } from '~/pages/event/state-mgmt/edu/edu-event-detail.action';
import { EduEventOtherDetailOutput, EduEventIllustrativePhotoOutput } from '~/pages/event/entities/edu-event-other-detail.types';
import { EduEventOtherDetailState } from '~/pages/event/state-mgmt/edu/edu-event-other-detail.state';
import { LoadEventOtherDetail, LoadEventOtherDetailPhotos } from '~/pages/event/state-mgmt/edu/edu-event-other-detail.actions';
import { withLatestFrom } from 'rxjs/operators';

@Component({
    selector: 'EduEventOtherDetailPage',
    moduleId: module.id,
    templateUrl: './edu-event-other-detail-page.component.html',
})
export class EduEventOtherDetailPageComponent {

    @Select(EduEventDetailState.getEventCourses)
    eventCourses$: Observable<EduEventCourseOutput[]>;
    @Select(EduEventOtherDetailState.getEventOtherDetail)
    eventOtherDetail$: Observable<EduEventOtherDetailOutput>;
    @Select(EduEventOtherDetailState.getEventOtherDetailPhotos)
    illustrativePhotos$: Observable<EduEventIllustrativePhotoOutput[]>;
    @Select(EduEventDetailState.getEventCourses)
    courses$: Observable<EduEventCourseOutput[]>;

    @Input()
    isLoading: ActionsExecuting;

    @Input()
    selectedIndex: number;
    @Input()
    eventId: number;
    selectedCourse: EduEventCourseOutput;

    constructor(
        private store: Store,
    ) {
    }

    refreshOtherDetail() {
        this.store.dispatch([
            new LoadEduEventCourses(this.eventId, this.eventId),
        ]).pipe(withLatestFrom(this.courses$)).subscribe(([_, courses]) => {
            if (courses.length === 1) {
                this.selectedCourse = courses[0]
            }
            this.loadCourse(this.selectedCourse && this.selectedCourse.ID);
        })
    }

    loadCourse(courseId: number) {
        this.store.dispatch([new LoadEventOtherDetail(this.eventId, courseId),
        new LoadEventOtherDetailPhotos(this.eventId, courseId)]);
    }
}
