import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Select, Store } from '@ngxs/store';
import { RouterExtensions } from '@nativescript/angular';
import { withLatestFrom } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { ActionsExecuting, actionsExecuting } from '@ngxs-labs/actions-executing';
import { CampEventDetailState } from '~/pages/event/state-mgmt/camp/camp-event-detail.state';
import { CampEventDetailOutput } from '~/pages/event/entities/camp-event-detail.types';
import { LoadCampEventDetail } from '~/pages/event/state-mgmt/camp/camp-event-detail.actions';
import { CampEventParticipantState } from '../../../state-mgmt/camp/camp-event-participant.state';
import { Degree, ParticipantCampInsertOutput } from '~/pages/event/entities/camp-event-participant.types';
import { CampEventLoadDegrees, CampParticipantSearchPerson, InsertCampEventParticipant } from '~/pages/event/state-mgmt/camp/camp-event-participant.actions';
import { transitionOptions } from '~/constants/shared.constants';
import { CampEventTabs } from '../camp-event-detail-page/camp-event-detail-page.component';
import { NewParticipantFormResult } from '~/pages/event/components/common/participant-form/participant-form.component';
import { CampPersonSearchContainerComponent } from '../../common/camp-person-search-container/camp-person-search-container.component';
import { SegmentedBarItem } from "@nativescript/core/ui/segmented-bar";
@Component({
    selector: 'AddCampEventParticipantPage',
    moduleId: module.id,
    templateUrl: './camp-event-add-participant-page.component.html',
})
export class AddCampEventParticipantPageComponent implements OnInit {
    @Select(actionsExecuting([
        LoadCampEventDetail,
        CampParticipantSearchPerson,
        InsertCampEventParticipant,
        CampEventLoadDegrees
    ]))
    isLoading$: Observable<ActionsExecuting>;
    @Select(CampEventDetailState.getEventDetail)
    eventDetail$: Observable<CampEventDetailOutput>;
    @Select(CampEventParticipantState.getDegrees)
    degrees$: Observable<Degree[]>;
    degrees: Degree[] = [];
    @Select(CampEventParticipantState.getNewParticipant)
    insertedParticipand$: Observable<ParticipantCampInsertOutput[]>
    @ViewChild('personForm', { static: false })
    personForm: CampPersonSearchContainerComponent;
    segmentedBarItems: SegmentedBarItem[] = [];

    eventId: number;
    findParticipant: boolean = true;

    submittableSearch = false;
    submittableCreate = false;
    opts = ['Vyhledat osobu', 'Zadat novou osobu'];
    selectedIndex = 0;

    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 LoadCampEventDetail(this.eventId),
                new CampEventLoadDegrees()])
        })
    }


    submit() {
        if (this.findParticipant) {
            const personId = this.personForm.selectedPersonId
            if (this.submittableSearch && personId) {
                if (personId) {
                    this.submitting(
                        this.store.dispatch(new InsertCampEventParticipant({
                            personId,
                            campId: this.eventId, newParticip: null
                        })))
                }
            }
        }
    }

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

    }

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

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

    private submitting(obs) {
        return obs.pipe(withLatestFrom(this.insertedParticipand$))
            .subscribe(([_, res]) => {
                if (res) {
                    setTimeout(() =>
                        this.routerExtensions.navigate(['event/campDetail/',
                            this.eventId, CampEventTabs.PARTICIPANTS],
                            { transition: transitionOptions }),
                        100)
                }
            })
    }

}
