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

import { AppService } from '../../app.service';
import { SorterModel } from '../../models/sorterModel';
import { WorkflowTemplateModel } from '../../models/workflowTemplateModel';
import { SearchService } from '../../oneit/services/search.service';
import { UtilsService } from '../../oneit/services/utils.service';
import { BaseComponent } from '../base/base.component';
import { ListWorkFlowsService } from './list-work-flows.service';

@Component({
  selector: 'app-list-work-flows',
  templateUrl: './list-work-flows.component.html'
})
export class ListWorkFlowsComponent extends BaseComponent implements OnInit {

  subscriptions: Array<Subscription> = [];
  myTemplates: Array<WorkflowTemplateModel> = [];
  sharedTemplates: Array<WorkflowTemplateModel> = [];
  sortOptions: Array<SorterModel>;
  sortSelected: SorterModel;
  showLoader = false;

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private utilsService: UtilsService,
    private searchService: SearchService,
    private appService: AppService,
    private listWorkFlowsService: ListWorkFlowsService
  ) {
    super(utilsService);
  }

  ngOnInit(): void {
    this.sortOptions = [
      new SorterModel('Alphabetical (A-Z)', true),
      new SorterModel('Alphabetical (Z-A)', false)
    ];
    const sharedParams = {
      OnlyGlobalTemplates: true
    };
    const myParams = {
      OnlyGlobalTemplates: false
    };
    this.subscriptions.push(
      this.listWorkFlowsService
        .getWorkFlows(myParams, [])
        .subscribe(
          messages => {
            this.myTemplates = messages;
          },
          error => {
            this.showLoader = false;
            this.utilsService.handleError(error);
          }
        )
    );
    this.subscriptions.push(
      this.listWorkFlowsService
        .getWorkFlows(sharedParams, [])
        .subscribe(
          messages => {
            this.sharedTemplates = messages;
          },
          error => {
            this.showLoader = false;
            this.utilsService.handleError(error);
          }
        )
    );
    setTimeout(() => (this.showLoader = false), 0);
  }

  sortWorkFlowTemplates(): void {
    this.showLoader = true;
    this.myTemplates = this.utilsService.sort(this.myTemplates,
      ['TemplateName'], [this.sortSelected.ascending ? 1 : -1], false);
    this.sharedTemplates = this.utilsService.sort(this.sharedTemplates,
      ['TemplateName'], [this.sortSelected.ascending ? 1 : -1], false);
    this.showLoader = false;
  }

  onRowSelect(data: WorkflowTemplateModel): void {
    this.showLoader = true;
    this.router.navigate(['/edit-work-flow', data.ObjectID]);
  }
}
