import { Component, ViewChild, OnInit } from '@angular/core';
import { RouterExtensions } from '@nativescript/angular';
import { Select, Store } from '@ngxs/store';
import { GenParticipantSearchPerson, LoadGenEventNewParticipationFunctionTypes, LoadGenEventNewParticipationQualificationTypes } from '~/pages/event/state-mgmt/gen/gen-event-participant.actions';
import { Observable } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';

import * as dialogs from "@nativescript/core/ui/dialogs";
import { Picker } from '~/pages/event/util';
import { ActivatedRoute } from '@angular/router';
import { actionsExecuting, ActionsExecuting } from '@ngxs-labs/actions-executing';
import { EduEventDeleteInstructor, EduEventInsertInstructor, EduEventUpdateInstructor } from '~/pages/event/state-mgmt/edu/edu-event-detail.action';
import { LoadEventInstructors, EduEventLoadInstructor, LoadEventInstructorTypes } from '~/pages/event/state-mgmt/edu/edu-event-people.actions';
import { EduEventInstructorsOutput } from '~/pages/event/entities/edu-event-people.types';
import { EduEventPeopleDetailState } from '~/pages/event/state-mgmt/edu/edu-event-people.state';
import { EduEventInstructorTypeAllOutput } from './../../../entities/edu-event-people.types';
import { EduEventDetailOutput } from '~/pages/event/entities/edu-event-detail.types';
import { EduEventDetailState } from '~/pages/event/state-mgmt/edu/edu-event-detail.state';
import { PersonSearchContainerComponent } from '../../common/person-search-container/person-search-container.component';

export interface EduEventInstructorInput {
    type: string;
    profExp: string;
    scoutExp: string;
    focus: string;
    personId: number;
}

@Component({
    selector: 'EduEventUpdateInstructorPage',
    moduleId: module.id,
    templateUrl: './edu-event-update-instructor-page.component.html',

})
export class EduEventUpdateInstructorPageComponent implements OnInit {

    @ViewChild('personSearch', { static: false })
    personSearch: PersonSearchContainerComponent

    @Select(actionsExecuting([
        GenParticipantSearchPerson, EduEventDeleteInstructor,
        LoadEventInstructors, LoadGenEventNewParticipationFunctionTypes,
        LoadEventInstructorTypes, LoadGenEventNewParticipationQualificationTypes,
        EduEventInsertInstructor, EduEventUpdateInstructor
    ]))
    isLoading$: Observable<ActionsExecuting>;
    @Select(EduEventPeopleDetailState.getEventSelectedInstructor)
    instructor$: Observable<EduEventInstructorsOutput>;
    @Select(EduEventPeopleDetailState.getInstructorTypes)
    instructorTypes$: Observable<EduEventInstructorTypeAllOutput[]>;
    @Select(EduEventDetailState.getEventDetail)
    eventDetail$: Observable<EduEventDetailOutput>;
    eventId: number;
    formattedInstructorTypes: Picker[] = []
    instructorForm = {
        type: null,
        profExp: '',
        scoutExp: '',
        focus: '',
    }
    instructorId: number;
    instructor: EduEventInstructorsOutput;
    canSubmit = false;

    constructor(
        private route: ActivatedRoute,
        private store: Store,
        private routerExtensions: RouterExtensions,) {
    }

    ngOnInit(): void {
        this.route.params.subscribe(params => {
            this.eventId = parseInt(params['id'], 10);

            this.store.dispatch([new LoadEventInstructorTypes(),
            ]).pipe(withLatestFrom(this.instructorTypes$)).subscribe(([_, types]) => {
                this.formattedInstructorTypes = types.map(t => ({ key: t.ID, label: t.DisplayName }))
            })
            if (params['instructorId']) {
                this.instructorId = parseInt(params['instructorId'], 10);
                this.canSubmit = true;
                this.store.dispatch([
                    new EduEventLoadInstructor(this.eventId, this.instructorId),
                ]).pipe(withLatestFrom(this.instructor$))
                    .subscribe(([_, inst]) => {
                        this.instructor = inst;
                        this.instructorForm = {
                            type: inst.ID_InstructorType,
                            profExp: inst.ProfessionalExperience,
                            scoutExp: inst.ScoutExperience,
                            focus: inst.EventFocus,
                        }
                    })
            }
        })
    }

    close() {
        this.routerExtensions.back()
    }

    handleSelectedPerson(id: number) {
        this.canSubmit = !!id;
    }

    deleteInstructor() {
        const opts = {
            title: "Smazáni instruktora",
            message: `Opravdu chcete odebrat ${this.instructor.Person} z instruktorů akce?`,
            okButtonText: "Ano",
            cancelButtonText: "Ne",
        };
        dialogs.confirm(opts).then(res => {
            if (res) {
                this.store.dispatch(new EduEventDeleteInstructor(this.instructor.ID))
                    .subscribe(() => {
                        this.cleanUpAndRedirect()
                    })
            }
        })
    }
    submit() {
        const { focus, scoutExp, type, profExp } = this.instructorForm;
        if (this.instructorId) {
            this.store.dispatch(new EduEventUpdateInstructor(this.eventId, {
                profExp, scoutExp,
                type,
                focus, personId: this.instructorId,
            })).subscribe(() => {
                this.cleanUpAndRedirect()
            })
        } else {
            const personId = this.personSearch.selectedPersonId
            if (personId) {
                this.store.dispatch(new EduEventInsertInstructor(this.eventId, {
                    profExp, scoutExp,
                    type,
                    focus, personId,
                })).subscribe(() => {
                    this.cleanUpAndRedirect()
                })
            }
        }
    }
    private cleanUpAndRedirect() {
        this.personSearch && this.personSearch.clear();
        this.instructorForm = {
            type: null,
            profExp: '',
            scoutExp: '',
            focus: '',
        }
        setTimeout(() => {
            this.routerExtensions.back()
            this.store.dispatch([new LoadEventInstructors(this.eventId)])
        }, 10)
    }

}
