import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';

import { Message, MenuItem } from 'primeng/primeng';

import { AppService } from './../../app.service';
import { UtilsService } from './../../oneit/services/utils.service';
import { SearchService } from './../../oneit/services/search.service';
import { ListMessagesService } from './list-messages.service';

import { ListMessage } from './list-messages.model';

@Component({
    selector: 'app-list-messages',
    templateUrl: './list-messages.component.html'
})
export class ListMessagesComponent implements OnInit, OnDestroy {
    
    subscriptions: Array<Subscription> = [];
    
    listMessage : ListMessage = new ListMessage();
    messages: any[] = [];
    showResults: boolean = false;
    orders: any[] = [];
    showLoader: boolean = false;
    
    constructor(
        private router: Router,
        private activatedRoute: ActivatedRoute,
        private utilsService: UtilsService,
        private searchService: SearchService,
        private appService: AppService,
        private listMessagesService: ListMessagesService
    ){
        
    }

    ngOnInit() {

        this.searchService.getLastSearchRequest("ListMessage").subscribe(
            data => {
                if (data != null) {
                    this.listMessage = data.queryParams;
                    this.getMessages(false);
                }
            }
        );
        this.getOrders();
    }
    

    getOrders() {
        this.subscriptions.push(this.listMessagesService.getorders([])
            .subscribe(
                data => {
                    this.orders = data;
                },
                error => {
                    this.utilsService.handleError(error);
                }
            )
        );
    }

    getMessages(saveSearch: boolean) {
        
        this.showResults    =   true;
        this.showLoader     =   true;
        let assocs          =   [];
        
        this.subscriptions.push(this.listMessagesService.getMessages(this.listMessage, assocs, saveSearch)
            .subscribe(
                data => {
                    this.messages = data;
                    this.showLoader = false;
                },
                error => {
                    this.showLoader = false;
                    this.utilsService.handleError(error);
                }
            )
        );
    }
        
    onRowSelect(data) {
        this.router.navigate(['/XXXX', data.ObjectID]);
    }
    
    ngOnDestroy(){
        this.utilsService.unsubscribeSubscriptions(this.subscriptions);
    }
}