import {Component} from '@angular/core';
import {SubscribingComponent} from "../../../shared/components/subscribing.component";
import {RecipeService} from "../../services/recipe.service";
import {EmployeePermission} from "../../../shared/model/employee";
import {AccountService} from "../../../accounts/services/account.service";
import {Recipe} from "../../../shared/model/recipe.model";
import {ActivatedRoute, Router} from "@angular/router";

@Component({
  selector: 'cre-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.sass']
})
export class ListComponent extends SubscribingComponent {
  recipes$ = this.recipeService.allSortedByCompany
  tableCols = ['name', 'description', 'sample', 'iconNotApproved', 'buttonView', 'buttonEdit']
  searchQuery = ""
  panelForcedExpanded = false
  recipesHidden = []

  constructor(
    private recipeService: RecipeService,
    private accountService: AccountService,
    router: Router,
    activatedRoute: ActivatedRoute
  ) {
    super(activatedRoute, router)
  }

  ngOnInit() {
    super.ngOnInit();
  }

  searchRecipe(recipe: Recipe) {
    if (this.searchQuery.length > 0) {
      this.panelForcedExpanded = true
    }
    const positive = this.searchString(recipe.name) ||
      this.searchString(recipe.description) ||
      this.searchString(recipe.sample.toString())
    this.recipesHidden[recipe.id] = !positive
    return positive
  }

  isCompanyHidden(companyRecipes: Recipe[]): boolean {
    return (this.searchQuery && this.searchQuery.length > 0) && companyRecipes.map(r => this.recipesHidden[r.id]).filter(r => !r).length <= 0
  }

  get hasEditPermission(): boolean {
    return this.accountService.hasPermission(EmployeePermission.EDIT_RECIPE)
  }

  private searchString(value: string): boolean {
    return value.toLowerCase().indexOf(this.searchQuery.toLowerCase()) >= 0
  }
}
