import {
  Component,
  OnInit,
  Output,
  EventEmitter
} from '@angular/core';
import { Anim } from './animation';
import { Service } from '@overflow/commons-typescript/model/discovery';

@Component({
  selector: 'of-discovery-search-filter',
  templateUrl: './search-filter.component.html',
  animations: Anim
})
export class SearchFilterComponent implements OnInit {

  services: Service[] = [];
  filterWord: string;
  filterServices = new Map<string, boolean>();

  @Output() search = new EventEmitter<string>();
  @Output() serviceSelect = new EventEmitter<Map<string, boolean>>();

  constructor(
  ) {
  }

  ngOnInit() {
  }

  onSearch(e) {
    if (e.key !== 'Enter') {
      return;
    }
    this.search.emit(this.filterWord);
  }

  addService(service: Service) {
    if (service.name.indexOf('Not Supported Service') >= 0) {
      const tempName = service.name.split('Perhaps ')[1].split('[')[0];
      service.name = '*' + tempName;
    }
    let exist = false;
    this.services.forEach(value => {
      if (value.name === service.name) {
        exist = true;
        return;
      }
    });
    if (!exist) {
      this.services.push(service);
      this.filterServices[service.name] = true;
    }
    this.serviceSelect.emit(this.filterServices);
  }

  onServiceFilter(e, service: Service) {
    // if (e.checked) {
    //   this.filterServices.push(service);
    // } else {
    //   const index = this.filterServices.indexOf(service);
    //   this.filterServices.splice(index, 1);
    // }

    this.serviceSelect.emit(this.filterServices);
  }

}
