import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Select, Store } from '@ngxs/store';
import { ModalDialogOptions, ModalDialogService, RouterExtensions } from '@nativescript/angular';
import { GenEventUpdateFunctions, GenEventUpdateReport, GenEventUpdateState, LoadGenEventDetail, LoadGenEventLeaders, LoadGenEventParticipants, LoadGenEventStatisticAll, SetGenEventParticipantSortParams } from './../../../state-mgmt/gen/gen-event-detail.actions';
import { map } from 'rxjs/operators';
import { GenEventDetailState } from '~/pages/event/state-mgmt/gen/gen-event-detail.state';
import { GenEventDetailOutput, GenEventFunctionAllOutput } from '../../../entities/gen-event-detail.types';
import { Observable } from 'rxjs';
import { ActionsExecuting, actionsExecuting } from '@ngxs-labs/actions-executing';
import { Person } from '~/pages/event/types/common.types';
import { ViewContainerRef } from '@angular/core';
import { DeleteGenEvent } from '~/pages/event/state-mgmt/gen/gen-event-new.actions';
import { transitionOptions } from '~/constants/shared.constants';
import { GenEventRemoveParticipant, GenEventUpdateParticipant } from '~/pages/event/state-mgmt/gen/gen-event-participant.actions';
import { EventLeaderUpdateModalInput, GenEventUpdateLeaderModal, TeamMember } from '../gen-event-update-leader-modal/gen-event-update-leader-modal.component';
import { editIcon } from '~/constants/icons';
import { groupByPersonId, mergePersonMap } from '~/pages/event/util';

export enum GenEventTabs {
    BASE_DETAIL = 0,
    TEAM = 1,
    PARTICIPANTS = 2,
    REPORT = 3,
    STATE = 4,
}
export interface GenEventReport {
    target: string;
    program: string
}

@Component({
    selector: 'GenEventDetailPage',
    moduleId: module.id,
    templateUrl: './gen-event-detail-page.component.html',
})
export class GenEventDetailPageComponent implements OnInit {
    @Select(actionsExecuting([
        LoadGenEventDetail, LoadGenEventLeaders,
        LoadGenEventParticipants, LoadGenEventStatisticAll,
        GenEventRemoveParticipant, GenEventUpdateParticipant,
        SetGenEventParticipantSortParams, GenEventUpdateState,
        GenEventUpdateReport

    ]))
    isLoading$: Observable<ActionsExecuting>;

    @Select(GenEventDetailState.getEventDetail)
    eventDetail$: Observable<GenEventDetailOutput>;
    @Select(GenEventDetailState.getEventLeaderDetail)
    eventLeaders$: Observable<GenEventFunctionAllOutput[]>;

    team$: Observable<Person[]>;

    selectedIndex = GenEventTabs.BASE_DETAIL;
    eventId: number;
    constructor(
        private routerExtensions: RouterExtensions,
        private route: ActivatedRoute,
        private store: Store,
        private _vcRef: ViewContainerRef,
        private _modalService: ModalDialogService,
    ) {
    }
    ngOnInit(): void {
        this.route.params.subscribe(params => {
            this.eventId = parseInt(params['id'], 10);
            this.selectedIndex = parseInt(params['section'], 10) || GenEventTabs.BASE_DETAIL;
        })

        this.team$ = this.eventLeaders$
            .pipe(map<GenEventFunctionAllOutput[], Person[]>(
                (leaders: GenEventFunctionAllOutput[]) => {
                    const leadersList = leaders.map(({ ID_Person, Person,
                        EventFunctionType, Note }) =>
                    ({
                        id: ID_Person, name: Person,
                        roles: [EventFunctionType],
                        extendedInfo: [
                            { title: EventFunctionType + ' poznámka', value: Note }
                        ],
                        otherInfo: ''
                    })
                    ).filter(l => l.id);
                    const groups = groupByPersonId(leadersList)

                    return mergePersonMap(groups).map(p => ({
                        ...p, roles: [],
                        otherInfo: p.roles.join(', ')
                    }));
                }))
    }
    loadEventDetail() {
        this.store.dispatch(new LoadGenEventDetail(this.eventId));
    }

    loadLeadersData() {
        this.store.dispatch(new LoadGenEventLeaders(this.eventId))
    }

    onEditTeam() {
        const team = this.store.selectSnapshot(GenEventDetailState.getEventLeaderDetail)
        const ctx: EventLeaderUpdateModalInput = {
            eventId: this.eventId,
            members: team.map(t => ({
                roleId: t.ID_EventFunctionType, memberId: t.ID_Person,
                roleName: t.EventFunctionType, memberName: t.Person, note: t.Note,
            }))
        };
        const options: ModalDialogOptions = {
            viewContainerRef: this._vcRef,
            context: ctx,
            fullscreen: true,
        };
        this._modalService.showModal(GenEventUpdateLeaderModal, options)
            .then((formResult: TeamMember[]) => {
                if (formResult) {
                    this.store.dispatch(new GenEventUpdateFunctions(this.eventId, formResult))
                        .toPromise().then(() => {
                            this.loadLeadersData();
                        })
                }
            });
    }

    onUpdateEventState({ eventId, currentStateId }) {
        this.store.dispatch(new GenEventUpdateState(eventId, currentStateId))
    }
    onUpdateEventReport({ eventId, target, program }) {
        this.store.dispatch(new GenEventUpdateReport(eventId, { target, program }))
    }
    onDeleteEvent(eventId: number) {
        this.store.dispatch(new DeleteGenEvent(eventId));
        setTimeout(() => {
            this.routerExtensions.navigate(['/event/general'], { transition: transitionOptions });
        }, 10);

    }

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

    setIndex(i) {
        this.selectedIndex = i.newIndex;
    }
    get editIcon() { return editIcon; }
}