import { Component, EventEmitter, Input, Output } from '@angular/core';
import { action } from '@nativescript/core/ui/dialogs';
import { PickerProvider } from '~/core/entities/picker-provider';
import { Item } from '~/shared/components/item-picker/item';

@Component({
    moduleId: module.id,
    selector: 'ItemPicker',
    templateUrl: './item-picker.component.html',
    styleUrls: ['./item-picker.component.scss']
})
export class ItemPickerComponent {
    isLoading = false;
    isDialogOpen = false;
    @Input() label: string;
    @Input() item: Item;
    @Input() vertical: boolean;
    @Output() selectedItem = new EventEmitter<number | string>(true);

    private _itemsProvider: PickerProvider[];

    get itemsProvider(): PickerProvider[] {
        return this._itemsProvider;
    }

    @Input('itemsProvider')
    set itemsProvider(value: PickerProvider[]) {
        this._itemsProvider = value;
        if (value && value.length > 0) {
            if (this._itemsProvider && this._itemsProvider.length > 0) {
                const selectedItem = this._itemsProvider.find((x: PickerProvider) => this.item && x.key === this.item.id);
                this.selectedItem.emit(selectedItem ? this.item.id : this._itemsProvider[0].key);
            }
        }
    }

    async showModalItemPicker() {
        this.isLoading = true;

        const options = {
            message: 'Vyberte položku',
            cancelButtonText: 'Zrušit',
            actions: this.itemsProvider.map(obj => obj.label)
        };

        this.isLoading = false;

        if (!this.isDialogOpen) {
            this.isDialogOpen = true;
            action(options).then(async (result) => {
                const item = this.itemsProvider.find(obj => obj.label === result);
                if (item) {
                    this.selectedItem.emit(item.key);
                }
                this.isDialogOpen = false;
            });
        }
    }

    get itemLabel() {
        if (this.item) {
            const pickerProvider = this._itemsProvider.find(x => x.key === this.item.id);

            return pickerProvider ? pickerProvider.label : 'Vyberte';
        } else {
            return 'Vyberte';
        }
    }
}
