import { Component, EventEmitter, Input, Output, ViewContainerRef, OnInit } from '@angular/core';
import { ActionsExecuting } from '@ngxs-labs/actions-executing';
import { Select, Store } from '@ngxs/store';
import { ModalDialogService, ModalDialogOptions } from '@nativescript/angular';
import { Observable, combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import { SortModalComponent } from '~/pages/event/components/common/sort-modal/sort-modal.component';
import { GenParticipant } from '~/pages/event/types/genEvent';
import { SortParams, formattedGenParticipantSortKeys, GenParticipantSortKey } from '~/pages/event/types/EventSorting';
import { GenEventParticipantAllOutput, GenEventStatisticOutput } from '~/pages/event/entities/gen-event-detail.types';
import { LoadGenEventParticipants, LoadGenEventStatisticAll, SetGenEventParticipantSortParams } from '~/pages/event/state-mgmt/gen/gen-event-detail.actions';
import { GenEventDetailState } from '~/pages/event/state-mgmt/gen/gen-event-detail.state';
import { GenEventRemoveParticipant, GenEventUpdateParticipant, GenEventUpdateParticipantStatisticAutoComputed } from '~/pages/event/state-mgmt/gen/gen-event-participant.actions';
import { sortItems } from '~/pages/event/util';
import { GenEventDetailOutput } from './../../../entities/gen-event-detail.types';

@Component({
    selector: 'GenEventParticipantPage',
    moduleId: module.id,
    templateUrl: './gen-event-participant-page.component.html',
})
export class GenEventParticipantPageComponent implements OnInit {

    @Input()
    isLoading: ActionsExecuting;
    @Select(GenEventDetailState.getParticipants)
    participants$: Observable<GenEventParticipantAllOutput[]>;
    @Select(GenEventDetailState.getParticipantStats)
    participantStats$: Observable<GenEventStatisticOutput[]>;
    @Select(GenEventDetailState.getGenParticipantsSortParams)
    sortParams$: Observable<SortParams>;


    @Input()
    isSelected: boolean
    @Input()
    eventId: number
    @Output()
    loadEventDetail = new EventEmitter()
    @Input()
    eventDetail: GenEventDetailOutput;

    genParticipants$: Observable<GenParticipant[]>;
    constructor(private store: Store,
        private _vcRef: ViewContainerRef,
        private _modalService: ModalDialogService,) {
    }

    ngOnInit(): void {
        this.genParticipants$ = combineLatest([this.participants$, this.sortParams$])
            .pipe(map(([particips, sortParams]) => {
                const sorted = sortItems(particips, sortParams,
                    sortParams.sortByKey === GenParticipantSortKey.BIRTHDAY);
                return this.refreshParticipants(sorted);
            }))
    }

    loadParticipants() {
        this.loadEventDetail.emit();
        this.store.dispatch([
            new LoadGenEventParticipants(this.eventId),
            new LoadGenEventStatisticAll(this.eventId)
        ])
    }

    removeParticipant(participId: number) {
        this.store.dispatch(new GenEventRemoveParticipant(participId))
    }

    updateParticipant(particip: GenParticipant) {
        this.store.dispatch(new GenEventUpdateParticipant({ particip }))
    }

    openSortModal() {
        const sortParams = this.store.selectSnapshot(GenEventDetailState.getGenParticipantsSortParams)
        const options: ModalDialogOptions = {
            viewContainerRef: this._vcRef,
            context: { sortParams: sortParams, formattedSortByKeys: formattedGenParticipantSortKeys },
            fullscreen: false,
        };
        this._modalService.showModal(SortModalComponent, options)
            .then((formResult: SortParams) => {
                if (formResult) {
                    this.store.dispatch(new SetGenEventParticipantSortParams(formResult))
                }
            });
    }

    updateAutoStats(value: boolean) {
        this.store.dispatch(new GenEventUpdateParticipantStatisticAutoComputed(this.eventId, value))
            .subscribe(() => {
                this.loadEventDetail.emit();
            });
    }

    refreshParticipants(particips: GenEventParticipantAllOutput[]): GenParticipant[] {
        return particips.map(
            ({ Person, Birthday, Street, Days, Age, UnitRegistrationNumber,
                ParticipantCategory, Note, ID, ID_Person }) =>
            ({
                ID, Name: Person,
                Category: ParticipantCategory, Address: Street,
                Days, Age, UnitNumber: UnitRegistrationNumber,
                Birthday, Note, PersonId: ID_Person,
            })
        ).filter(l => l.ID);
    }
}
