import { Component, ViewChild, OnInit } from '@angular/core';
import { RouterExtensions } from '@nativescript/angular';
import { Select, Store } from '@ngxs/store';
import { GenParticipantSearchPerson, LoadGenEventNewParticipationFunctionTypes, LoadGenEventNewParticipationQualificationTypes } from '~/pages/event/state-mgmt/gen/gen-event-participant.actions';
import { Observable } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { GenEventParticipantState } from '~/pages/event/state-mgmt/gen/gen-event-participant.state';
import * as dialogs from "@nativescript/core/ui/dialogs";
import { transitionOptions } from '~/constants/shared.constants';
import { ActivatedRoute } from '@angular/router';
import { actionsExecuting, ActionsExecuting } from '@ngxs-labs/actions-executing';
import { TeamMember } from '../../gen/gen-event-update-leader-modal/gen-event-update-leader-modal.component';
import { EduEventDeleteAssistant, EduEventUpdateAssistant, EduEventUpdateLeader } from '~/pages/event/state-mgmt/edu/edu-event-detail.action';
import { LoadEventLeaderDetail, LoadEventAssistantDetail } from '~/pages/event/state-mgmt/edu/edu-event-people.actions';
import { EduEventLeaderDetailOutput, EduEventAssistantOutput } from '~/pages/event/entities/edu-event-people.types';
import { EduEventPeopleDetailState } from '~/pages/event/state-mgmt/edu/edu-event-people.state';
import { EduEventInsertAssistant } from './../../../state-mgmt/edu/edu-event-detail.action';
import { PersonSearchContainerComponent } from '../../common/person-search-container/person-search-container.component';
import { deleteIcon, editIcon } from '~/constants/icons';

@Component({
    selector: 'EduEventUpdateLeadderPage',
    moduleId: module.id,
    templateUrl: './edu-event-update-leader-page.component.html',
})
export class EduEventUpdateLeaderPageComponent implements OnInit {
    @ViewChild('personSearch', { static: true })
    personSearch: PersonSearchContainerComponent

    @Select(actionsExecuting([
        LoadGenEventNewParticipationQualificationTypes,
        LoadGenEventNewParticipationFunctionTypes,
        GenParticipantSearchPerson, EduEventDeleteAssistant,
        LoadEventLeaderDetail, LoadEventAssistantDetail,
        EduEventInsertAssistant, EduEventUpdateLeader
    ]))
    isLoading$: Observable<ActionsExecuting>;
    @Select(EduEventPeopleDetailState.getEventLeaderDetail)
    eventLeaders$: Observable<EduEventLeaderDetailOutput[]>;
    @Select(EduEventPeopleDetailState.getEventAssistantsDetail)
    eventAssistants$: Observable<EduEventAssistantOutput[]>;
    members: TeamMember[] = [];
    eventId: number;
    canSelectFunction: boolean;
    noteForm = { note: '' }
    leaders: EduEventLeaderDetailOutput[] = [];
    deleteIcon = deleteIcon;
    editIcon = editIcon;

    constructor(
        private route: ActivatedRoute,
        private store: Store,
        private routerExtensions: RouterExtensions,) {
    }

    ngOnInit(): void {
        this.route.params.subscribe(params => {
            this.eventId = parseInt(params['id'], 10);
            this.store.dispatch([
                new LoadEventLeaderDetail(this.eventId),
                new LoadEventAssistantDetail(this.eventId)
            ]).pipe(withLatestFrom(this.eventLeaders$))
                .subscribe(([_, leaders]) => {
                    this.members = leaders.map(t => ({
                        roleId: t.ID_EventFunctionType, memberId: t.ID_Person,
                        roleName: t.EventFunctionType, memberName: t.Person, note: t.Note,
                    }));
                    this.leaders = leaders;
                })
            this.canSelectFunction = false
        })

    }
    close() {
        this.routerExtensions.back()
    }
    handleSelectedPerson(id: number) {
        this.canSelectFunction = !!id;
    }

    deleteLeader(member: TeamMember) {
        member.memberId = null;
        member.memberName = null;
        member.note = null;
        this.canSelectFunction = !!this.personSearch.selectedPersonId
    }
    updateNote(member: TeamMember) {
        const opts = {
            title: "Upravit poznámku",
            message: "Poznámka pro " + member.memberName,
            okButtonText: "Upravit",
            cancelButtonText: "Zrušit",
            defaultText: member.note,
        };
        dialogs.prompt(opts).then((r) => {
            member.note = r.text;
        });
    }

    deleteAssistant(assistant: EduEventAssistantOutput) {
        const opts = {
            title: "Smazáni asistenta",
            message: `Opravdu chcete odebrat ${assistant.Person} z asistentů vedoucího akce?`,
            okButtonText: "Ano",
            cancelButtonText: "Ne",
        };
        dialogs.confirm(opts).then(res => {
            if (res) {
                this.store.dispatch(new EduEventDeleteAssistant(this.eventId, assistant.ID))
                    .subscribe(() => {
                        this.store.dispatch(new LoadEventAssistantDetail(this.eventId))
                    })
            }
        })
    }
    updateAssistant(assistant: EduEventAssistantOutput) {
        const opts = {
            title: "Upravit poznámku",
            message: "Poznámka pro " + assistant.Person,
            okButtonText: "Upravit",
            cancelButtonText: "Zrušit",
            defaultText: assistant.Note,
        };
        dialogs.prompt(opts).then((r) => {
            if (r) {
                this.store.dispatch(
                    new EduEventUpdateAssistant(this.eventId,
                        {
                            memberId: assistant.ID_Person,
                            note: r.text,
                            memberName: assistant.Person,
                            roleId: assistant.ID,
                            roleName: assistant.EventFunctionType,

                        })).subscribe(() => {
                            this.store.dispatch(new LoadEventAssistantDetail(this.eventId))
                        })
            }
        });
    }

    assignFunction() {
        const actions = this.members.map(p => p.roleName)
        const userId = this.personSearch.selectedPersonId
        const personList = this.store.selectSnapshot(GenEventParticipantState.getPersonList)
        const person = personList.find(p => p.ID === userId)
        actions.push('Zástupce vedoucího')
        dialogs.action({
            title: 'Vyberte funkci',
            message: "Vyberte funkci pro " + person.DisplayName,
            cancelButtonText: "Zrušit",
            actions,
        }).then((result) => {
            const personId = userId
            if (result === 'Zástupce vedoucího') {
                this.store.dispatch(
                    new EduEventInsertAssistant(this.eventId,
                        {
                            memberId: personId,
                            note: this.noteForm.note,
                            memberName: person.DisplayName,
                            roleId: undefined,
                            roleName: undefined,
                        })).subscribe(() => {
                            this.store.dispatch(new LoadEventAssistantDetail(this.eventId))
                        })
            } else {
                const selectedMember = this.members.find(m => m.roleName === result);
                selectedMember.memberId = personId;
                selectedMember.note = this.noteForm.note;
                selectedMember.memberName = person.DisplayName
            }
            this.personSearch.clear()
            this.noteForm = { note: '' };
            this.canSelectFunction = false
        });
    }

    submit() {
        const merged = this.members
            .map(({ note, memberId, memberName, roleId, roleName }) => ({
                ...this.leaders.find(p => p.EventFunctionType === roleName),
                Note: note, ID_Person: memberId,
                ID_EventFunctionType: roleId, Person: memberName,
                EventFunctionType: roleName
            }))
        this.store.dispatch(new EduEventUpdateLeader(this.eventId, merged))
            .subscribe(() => {
                this.routerExtensions.navigate(['/event/educationDetail/', this.eventId, 2], { transition: transitionOptions });
            })
    }


}
