import { Component, EventEmitter, Input, Output } from '@angular/core';
import { isAndroid } from 'nativescript-platform';
import { ListViewEventData, ListViewScrollEventData } from 'nativescript-ui-listview';
import { TOP_ACTION_BAR_HEIGHT } from '../disappearing-scroll-action-bar/disappearing-scroll-action-bar.component';
export interface ListType {
    extended: boolean;
}
@Component({
    selector: 'ScrollTopBarList',
    moduleId: module.id,
    template: '',
})
export class ScrollTopBarListComponent<T extends ListType> {
    @Output()
    onScroll = new EventEmitter<number>();
    @Input()
    topBarHeight: number = TOP_ACTION_BAR_HEIGHT;
    private currOffset = 0;
    scrolled(args: ListViewScrollEventData) {
        if (Math.abs(args.scrollOffset - this.currOffset) > this.topBarHeight || args.scrollOffset === 0) {
            this.onScroll.emit(args.scrollOffset)
            this.currOffset = args.scrollOffset
        }
    }

    selectedIndex: number = null;

    @Input()
    set items(evs: T[]) {
        this._itemList = evs ? evs.map(o => ({ ...o, extended: false })) : []
    }
    get items() {
        return this._itemList;
    }
    _itemList: T[] = [];

    templateSelector = (item: ListType, index: number, items: any) =>
        item.extended && "selected";

    onItemTap(event: ListViewEventData) {
        const listView = event.object,
            rowIndex = event.index,
            dataItem = event.view.bindingContext;
        const prev = dataItem.extended;
        if (this.selectedIndex !== null) {
            this._itemList[this.selectedIndex].extended = false;
        }
        dataItem.extended = !prev;
        if (isAndroid) {
            listView.androidListView.getAdapter().notifyItemChanged(rowIndex);
        }
        this.selectedIndex = dataItem.extended ? rowIndex : null;
    }
}
