import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { RouterExtensions } from '@nativescript/angular';
import { Page } from '@nativescript/core';
import { Select, Store } from '@ngxs/store';
import { ListViewEventData } from 'nativescript-ui-listview';
import { Observable } from 'rxjs';
import { transitionOptions } from '~/constants/shared.constants';
import { MessageAllWebOutput } from '~/pages/message/entities/output/messageAllWebOutput';
import { LoadMessageAllWeb } from '~/pages/message/state-mgmt/message.actions';
import { MessageState } from '~/pages/message/state-mgmt/message.state';

@Component({
    selector: 'Message',
    moduleId: module.id,
    templateUrl: './message.component.html',
    styleUrls: ['./_message.component.scss']
})
export class MessageComponent implements OnInit {
    @Select(MessageState.getMessageAllWeb) messages$: Observable<MessageAllWebOutput[]>;
    @Select(MessageState.isLoading) isLoading$: Observable<boolean>;
    messages: MessageAllWebOutput[];

    constructor(
        private router: Router,
        private routerExtensions: RouterExtensions,
        private store: Store,
        private page: Page
    ) {
        this.page.on(Page.navigatingToEvent, () => {
            this.store.dispatch(new LoadMessageAllWeb());
        });
    }

    ngOnInit() {
        this.messages$.subscribe(messages => {
            this.messages = messages;
        });
    }

    onBackButton(): void {
        this.routerExtensions.back();
        // this.routerExtensions.navigate(['/home'], { transition: transitionOptions });
    }

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

    onItemTap(event: ListViewEventData) {
        setTimeout(() => {
            this.routerExtensions.navigate(['message/list', this.messages[event.index].ID], {transition: transitionOptions});
        }, 10);
    }

    onPullToRefreshInitiated(args: ListViewEventData) {
        this.store.dispatch(new LoadMessageAllWeb());
    }

}
