import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { actionsExecuting, ActionsExecuting } from '@ngxs-labs/actions-executing';
import { Select, Store } from '@ngxs/store';
import { RouterExtensions } from '@nativescript/angular';
import { Observable } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { transitionOptions } from '~/constants/shared.constants';
import { GenEventDetailOutput } from '~/pages/event/entities/gen-event-detail.types';
import { ParticipantGenInsertOutput } from '~/pages/event/entities/gen-event-participant.types';
import { LoadGenEventDetail } from '~/pages/event/state-mgmt/gen/gen-event-detail.actions';
import { GenEventDetailState } from '~/pages/event/state-mgmt/gen/gen-event-detail.state';
import { GenParticipantInsert, GenParticipantSearchPerson, LoadGenEventNewParticipationFunctionTypes, LoadGenEventNewParticipationQualificationTypes } from '~/pages/event/state-mgmt/gen/gen-event-participant.actions';
import { GenEventParticipantState } from '~/pages/event/state-mgmt/gen/gen-event-participant.state';
import { GenEventTabs } from '../gen-event-detail-page/gen-event-detail-page.component';
import { EventData } from '@nativescript/core/ui/page';
import { Switch } from '@nativescript/core/ui/switch';
import { NewParticipantFormResult } from '~/pages/event/components/common/participant-form/participant-form.component';
import { PersonSearchContainerComponent } from '../../common/person-search-container/person-search-container.component';
import { SegmentedBarItem } from '@nativescript/core/ui/segmented-bar';

@Component({
    selector: 'AddGenEventParticipantPage',
    moduleId: module.id,
    templateUrl: './Gen-event-add-participant-page.component.html',
})
export class AddGenEventParticipantPageComponent implements OnInit {
    @Select(actionsExecuting([
        LoadGenEventDetail,
        GenParticipantSearchPerson,
        LoadGenEventNewParticipationQualificationTypes,
        LoadGenEventNewParticipationFunctionTypes,
    ]))
    isLoading$: Observable<ActionsExecuting>;
    @Select(GenEventDetailState.getEventDetail)
    eventDetail$: Observable<GenEventDetailOutput>;
    @Select(GenEventParticipantState.getNewParticipant)
    insertedParticipand$: Observable<ParticipantGenInsertOutput[]>

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

    eventId: number;
    findParticipant: boolean = true;

    submittable = false;
    opts = ['Vyhledat osobu', 'Zadat novou osobu'];
    selectedIndex = 0;
    segmentedBarItems: SegmentedBarItem[] = [];


    constructor(
        private routerExtensions: RouterExtensions,
        private route: ActivatedRoute,
        private store: Store,
    ) {
        this.segmentedBarItems = this.opts.map(o => {
            const i = new SegmentedBarItem();
            i.title = o;
            return i
        })

    }

    public onSelectedIndexChange(args) {
        this.selectedIndex = args.value;
        this.findParticipant = args.value === 0;
    }
    ngOnInit(): void {
        this.route.params.subscribe(params => {
            this.eventId = parseInt(params['id'], 10);
            this.store.dispatch([
                new LoadGenEventDetail(this.eventId),
            ])
        })
    }

    submit() {
        const personId = this.personForm.selectedPersonId
        if (this.submittable && personId) {
            if (personId) {
                return this.redirectAfterInsert(this.store.dispatch(
                    new GenParticipantInsert({
                        personId,
                        genId: this.eventId, newParticip: null
                    })))
            }
        }
    }
    handleSelectedPerson(id: number) {
        this.submittable = !!id;
    }


    onNewSubmit({ degrees, info }: NewParticipantFormResult) {
        if (!this.findParticipant) {
            const { nickName, lastName, firstName, note } = info;
            return this.redirectAfterInsert(this.store.dispatch(
                new GenParticipantInsert({
                    personId: null,
                    genId: this.eventId, newParticip: {
                        note, firstName, lastName,
                        nickName, degrees, contacts: undefined
                    }
                })))
        }

    }

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

    onCheckedChange(args: EventData) {
        const sw = args.object as Switch;
        this.findParticipant = sw.checked;
    }

    private redirectAfterInsert(obs: Observable<any>) {
        return obs.pipe(withLatestFrom(this.insertedParticipand$))
            .subscribe(([_, res]) => {
                if (res) {
                    setTimeout(() => this.routerExtensions.navigate(['event/generalDetail/',
                        this.eventId, GenEventTabs.PARTICIPANTS], { transition: transitionOptions }),
                        100)
                }
            })
    }

}
