import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { map, withLatestFrom } from 'rxjs/operators';
import { SelectPersonFormComponent } from '~/pages/event/components/common/select-person-form/select-person-form.component';
import { CampEventParticipantResetSearch, CampParticipantSearchPerson } from '~/pages/event/state-mgmt/camp/camp-event-participant.actions';
import { CampEventParticipantState } from '~/pages/event/state-mgmt/camp/camp-event-participant.state';
import { Picker, pickPersonModal } from '~/pages/event/util';

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

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

    @ViewChild('personSearch', { static: true })
    personSearch: SelectPersonFormComponent
    @Output()
    onSelectedPerson = new EventEmitter<number>()

    constructor(private store: Store) {
    }

    ngOnInit(): void {
        this.personList$ = this.store.select(CampEventParticipantState.getPersonList)
            .pipe(map(personList =>
                personList.map(p =>
                    ({ key: p.ID.toString(), label: p.DisplayName }))
            ))
    }
    handleSearch = ({ criteria, text, }) => {
        this.store.dispatch(new CampParticipantSearchPerson({
            criteria: criteria, text,
            eventId: this.eventId,
        })).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.store.dispatch(new CampEventParticipantResetSearch())
        this.personSearch.clear()
    }

}
