import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Select, Store } from '@ngxs/store';
import { RouterExtensions } from '@nativescript/angular';
import { Observable } from 'rxjs';
import { Switch } from '@nativescript/core/ui/switch';
import { withLatestFrom } from 'rxjs/operators';
import { EduEventCourseDetailEnrollOutput, EventQuestionAllOutput } from '~/pages/event/entities/edu-event.types';
import { EduEventActionState } from '~/pages/event/state-mgmt/edu/edu-event-action.state';
import { LoadEduEventQuestionAll, LoadEventEnrollDetail } from '~/pages/event/state-mgmt/edu/edu-event.actions';
import { EduEventDetailState } from '~/pages/event/state-mgmt/edu/edu-event-detail.state';
import { EduEventDetailOutput } from './../../../entities/edu-event-detail.types';
import { actionsExecuting, ActionsExecuting } from '@ngxs-labs/actions-executing';
import { openUrl } from '@nativescript/core/utils/utils';
import { LoadEduEventDetail } from './../../../state-mgmt/edu/edu-event-detail.action';
import { SKAUTIS_EDU_EVENT_ENROLL_URL } from '~/pages/event/util/event';

@Component({
    selector: 'EduEventEnrollPage',
    moduleId: module.id,
    templateUrl: './edu-event-enroll-page.component.html',
    styleUrls: ['./_edu-event-enroll-page.component.scss'],
})
export class EduEventEnrollPageComponent implements OnInit {
    @Select(EduEventActionState.getEventLeaderDetail)
    enrollDetail$: Observable<EduEventCourseDetailEnrollOutput>;
    @Select(EduEventActionState.getEnrollQuestions)
    eventQuestions$: Observable<EventQuestionAllOutput[]>;
    @Select(EduEventDetailState.getEventDetail)
    eventDetail$: Observable<EduEventDetailOutput>

    @Select(actionsExecuting([
        LoadEventEnrollDetail,
        LoadEduEventDetail,
        LoadEduEventQuestionAll,
    ]))
    isLoading$: Observable<ActionsExecuting>;

    _enrollDetail: EduEventCourseDetailEnrollOutput;
    eventId: number;
    courseId: number;
    eventQuestions: EventQuestionAllOutput[];
    declaration: boolean;
    hasRequiredFileUpload: boolean;
    //TODO if file upload field is required or the other required option then this enrollment cannot be finished in mobile app
    questionTypes = {
        Info: 'Informační text',
        OneLine: 'Jednořádkový text',
        Switch: 'Přepínač Ano/Ne',
        File: 'Přiložení souboru',
        MultiLine: 'Víceřádkový text'
    };
    questionRequirements = {
        NotRequired: 'Nepovinné',
        RequiredWhenSending: 'Povinné při odevzdání přihlášky',
        Required: 'Povinné'
    }
    eventDetail: EduEventDetailOutput;
    constructor(
        private routerExtensions: RouterExtensions,
        private route: ActivatedRoute,
        private store: Store,
    ) {
    }
    ngOnInit(): void {
        this.route.params.subscribe(params => {
            this.eventId = parseInt(params['eventId'], 10);
            this.courseId = parseInt(params['courseId'], 10);
            if (this.eventId && this.courseId) {
                this.store.dispatch(
                    [new LoadEventEnrollDetail(this.courseId),
                    new LoadEduEventDetail(this.eventId)]
                ).pipe(withLatestFrom(this.enrollDetail$, this.eventDetail$))
                    .subscribe(([_, detail, eventDetail]) => {
                        this._enrollDetail = detail;
                        this.eventDetail = eventDetail
                        // TODO broken api, cant load user answers -> future work
                        // this.store.dispatch(new LoadEduEventQuestionAll(this.eventId,
                        //     this.courseId, detail.ID_ParticipantEducation))
                        //     .pipe(withLatestFrom(this.eventQuestions$))
                        //     .subscribe(([_, res]) => {
                        //         this.eventQuestions = res
                        //         this.hasRequiredFileUpload = res
                        //             .some(q => q.QuestionType === this.questionTypes.File &&
                        //                 (q.QuestionRequirement === this.questionRequirements.RequiredWhenSending))
                        //     })
                    })
            }
        })
    }
    onDeclarationChange(e) {
        const sw = e.object as Switch;
        if (sw) {
            this._enrollDetail.Agreement = sw.checked;
        }
    }
    handleEnroll() {
        // TODO fix this endpoint input
        // this.store.dispatch(new UpdateEventEducationCourseEnrollment({
        //     acknowledgement: false, affirmation: true,
        //     eventId: this.eventId, phone: this._enrollDetail.PersonPhone,
        //     questions: this.eventQuestions, verdictHealth: 'ok'
        // }))
    }

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

    onShowRegistration() {
        const { ID, ID_EventEducation } = this._enrollDetail
        const skuatIsUrl = `${SKAUTIS_EDU_EVENT_ENROLL_URL}?ID_EventEducationCourse=${ID}&ID_EventEducation=${ID_EventEducation}`;
        let url = this.eventDetail.LoginSkautis ? skuatIsUrl : this.eventDetail.LoginLocation;
        if (!url.startsWith('http://') && !url.startsWith('https://')) {
            url = 'http://' + url
        }
        openUrl(url)
    }


}