import {Component, OnInit} from '@angular/core';
import {Category} from './models/category';
import {CategoryService} from './services/category.service';
import {Observable} from 'rxjs/Observable';

@Component({
  selector: 'app-categories',
  template: `
    <h3>Categories</h3>
    
    <input #searchBox class="search" type="text" autofocus placeholder="Search Categories" (keyup)="search(searchBox.value)" (keyup.esc)="searchBox.value = null; search(null)"/>
    <div class="action-bar">
      <button class="button right" (click)="searchBox.value = null; ngOnInit()">Refresh</button>
      <a class="button" routerLink="/categories/add">Add Category</a>
    </div>

    <div class="alert alert-err" *ngIf="error">Something went wrong</div>

    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th width="20%">Rules</th>
          <th style="width: 30px"></th>
        </tr>
      </thead>
      <tbody>
        <tr class="category-row" *ngFor="let c of categories">
          <td><a [routerLink]="['/categories/edit', c.categoryId]">{{c.categoryName}}</a></td>
          <td>{{c.numberOfRules}}</td>
          <td><span class="fa fa-times" aria-hidden="true" (click)="deleteCategory(c.categoryId)" style="cursor: pointer"></span></td>
        </tr>
      </tbody>
    </table>
  `
})
export class CategoriesComponent implements OnInit {

  error = false;
  categories: Category[];
  _categories: Category[];

  search(searchTerm: string): void {
    this.categories = !searchTerm ? this._categories
      : this._categories.filter(c => c.categoryName.includes(searchTerm));
  }

  constructor(private categoryService: CategoryService) {}

  deleteCategory(categoryId: number): void {
    this.categoryService.deleteCategory(categoryId)
      .subscribe(
        () => this.loadCategories(),
        () => this.error = true);
  }

  loadCategories(): void {
    this.categoryService.get()
      .subscribe(cats => {
        this._categories = cats;
        this.search(null);
      });
  }


  ngOnInit(): void {
    this.loadCategories();
  }
}