import { Component } from '@angular/core';
import { ModalDialogParams } from '@nativescript/angular';
import { isAndroid, isIOS } from '@nativescript/core';
import { ListViewEventData } from 'nativescript-ui-listview';

declare var UIView;
declare var NSMutableArray;
declare var NSIndexPath;

@Component({
    moduleId: module.id,
    selector: 'StsDetailUpdateFupModal',
    templateUrl: './sts-detail-update-fup-modal.component.html',
    styleUrls: ['./sts-detail-update-fup-modal.component.scss']
})
export class StsDetailUpdateFupModalComponent {
    wasUpdated: boolean;
    fupTypes: any[];

    constructor(
        private params: ModalDialogParams
    ) {
        this.fupTypes = params.context.fupTypes
            .map(fupType => ({ ...fupType, selected: false }));

        this.wasUpdated = params.context.wasUpdated;
    }

    close() {
        this.params.closeCallback();
    }

    updateFUP() {
        const selectedFupType = this.fupTypes.find((fupType => fupType.selected === true));
        this.params.closeCallback(selectedFupType);
    }

    isFupTypeSelected() {
        return this.fupTypes.find((fupType => fupType.selected === true)) !== undefined;
    }

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

    onItemTap(event: ListViewEventData) {
        const listView = event.object;
        const rowIndex = event.index;
        const dataItem = event.view.bindingContext;

        this.fupTypes = this.fupTypes.map(fupType => {
            if (fupType.ID !== dataItem.ID) {
                fupType.selected = false;
            }

            return fupType;
        });

        dataItem.selected = !dataItem.selected;
        if (isIOS) {
            // Uncomment the lines below to avoid default animation
            // UIView.animateWithDurationAnimations(0, () => {
            const indexPaths = NSMutableArray.new();
            indexPaths.addObject(NSIndexPath.indexPathForRowInSection(rowIndex, event.groupIndex));
            listView.ios.reloadItemsAtIndexPaths(indexPaths);
            // });
        }
        if (isAndroid) {
            listView.androidListView.getAdapter().notifyItemChanged(rowIndex);
        }
    }
}
