import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { Select, Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { map, withLatestFrom } from 'rxjs/operators';
import { Picker, pickPersonModal } from '~/pages/event/util';
import { SelectPersonExtendedFormComponent } from '~/pages/event/components/common/select-person-extended-form/select-person-extended-form.component';
import { GenEventParticipantState } from '~/pages/event/state-mgmt/gen/gen-event-participant.state';
import { QualificationAllOutput } from '~/pages/search-person/entities/output/qualificationAllOutput';
import { GenEventParticipantResetSearch, GenParticipantSearchPerson, LoadGenEventNewParticipationFunctionTypes, LoadGenEventNewParticipationQualificationTypes } from '~/pages/event/state-mgmt/gen/gen-event-participant.actions';

@Component({
    selector: 'PersonSearchContainer',
    moduleId: module.id,
    template: `
    <SelectPersonExtendedForm #personSearch [personList]="personList$|async" (onSearch)="handleSearch($event)"
            [qualifications]="qualifications$|async" [functions]="functions$|async"></SelectPersonExtendedForm>`
})
export class PersonSearchContainerComponent implements OnInit {

    personList$: Observable<Picker[]>;
    get selectedPersonId() {
        return parseInt(this.personSearch.selectedPersonId)
    }
    @Input()
    eventId: number;

    @ViewChild('personSearch', { static: true })
    personSearch: SelectPersonExtendedFormComponent
    @Output()
    onSelectedPerson = new EventEmitter<number>()
    @Select(GenEventParticipantState.getFunctions)
    functions$: Observable<QualificationAllOutput[]>
    @Select(GenEventParticipantState.getQualifications)
    qualifications$: Observable<QualificationAllOutput[]>

    constructor(private store: Store) {
    }

    ngOnInit(): void {
        this.store.dispatch([
            new LoadGenEventNewParticipationQualificationTypes(),
            new LoadGenEventNewParticipationFunctionTypes(),
        ])
        this.personList$ = this.store.select(GenEventParticipantState.getPersonList)
            .pipe(map(personList =>
                personList.map(p =>
                    ({ key: p.ID.toString(), label: p.DisplayName }))
            ))
    }

    handleSearch({ criteria, text, functionId, qualificationId, onlyDirectUnits, unitRegistrationNumber }) {
        this.store.dispatch(new GenParticipantSearchPerson({
            criteria: criteria, text,
            eventId: this.eventId,
            qualificationId,
            functionId,
            unitRegistrationNumber,
            onlyDirectUnits,
        }))
            .pipe(withLatestFrom(this.personList$))
            .subscribe(([_, personList]) => {
                if (personList.length)
                    this.select(personList[0].key)
                pickPersonModal<Picker>(d => d.label, personList)
                    .then((result) => {
                        if (result) {
                            const { key } = personList.find(u => u.label === result);
                            this.select(key)
                        }
                    });
            })
    }

    private select(id: string) {
        this.onSelectedPerson.emit(parseInt(id));
        this.personSearch.selectedPersonId = id;
    }
    clear() {
        this.personSearch.clear();
        this.store.dispatch(new GenEventParticipantResetSearch())
    }

}
