import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { RouterExtensions } from '@nativescript/angular';
import { Select, Store } from '@ngxs/store';
import { FeedbackType } from 'nativescript-feedback';
import { Observable } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { feedbackMessage } from '~/pages/material/utils/feedback-messages';
import { ExportPersonAllOutput } from '../../entities/output/exportPersonAllOutput';
import { LoadExportPersonAll } from '../../state-mgmt/export-new.actions';
import { ExportNewState } from '../../state-mgmt/export-new.state';

@Component({
    selector: 'TemplatePicker',
    moduleId: module.id,
    templateUrl: './template-picker.component.html',
    styleUrls: ['./_template-picker.component.scss']
})

export class TemplatePickerComponent implements OnInit {
    @Select(ExportNewState.getExportPersonAll) exportPersonAll$: Observable<ExportPersonAllOutput[]>;
    @Select(ExportNewState.isLoading) isLoading$: Observable<boolean>;

    @Output() templatePicked = new EventEmitter<number>();

    items: ExportPersonAllOutput[] = [];

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

    ngOnInit(): void {
        this.store.dispatch(new LoadExportPersonAll())
            .pipe(withLatestFrom(this.exportPersonAll$))
            .subscribe(([_, insert]) => {
                this.items = insert;
            }, err => {
                console.log(err);
                feedbackMessage(FeedbackType.Error, 'Načítání šablon', `Při načítání šablon došlo k chybě. Zkontrolujte prosím vaše internetové připojení.`);
                this.routerExtensions.back();
            });
    }

    onTapItem(item) {
        this.templatePicked.emit(item.ID);
    }

    templateSelector(item: any, index: number, items: any): string {
        return 'default';
    }
}
