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 { ListWorkFlowsService } from './list-work-flows.service';

import { ListWorkFlow } from './list-work-flows.model';

@Component({
    selector: 'app-list-work-flows',
    templateUrl: './list-work-flows.component.html'
})
export class ListWorkFlowsComponent implements OnInit, OnDestroy {
    
    subscriptions: Array<Subscription> = [];
    
    listWorkFlow : ListWorkFlow = new ListWorkFlow();
    workFlows: 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 listWorkFlowsService: ListWorkFlowsService
    ){
        
    }

    ngOnInit() {

        this.searchService.getLastSearchRequest("ListWorkFlow").subscribe(
            data => {
                if (data != null) {
                    this.listWorkFlow = data.queryParams;
                    this.getWorkFlows(false);
                }
            }
        );
        this.getOrders();
    }
    

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

    getWorkFlows(saveSearch: boolean) {
        
        this.showResults    =   true;
        this.showLoader     =   true;
        let assocs          =   [];
        
        this.subscriptions.push(this.listWorkFlowsService.getWorkFlows(this.listWorkFlow, assocs, saveSearch)
            .subscribe(
                data => {
                    this.workFlows = 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);
    }
}