import { Component, EventEmitter, Input, Output } from '@angular/core';

import { Recipe } from 'src/app/shared/interfaces/services/api-fit/response/recipe.interface';
import { ApiFitService } from 'src/app/shared/services/api-fit/api-fit.service';

@Component({
  selector: 'app-recipe-card',
  templateUrl: './recipe-card.component.html',
  styleUrls: ['./recipe-card.component.scss'],
})
export class RecipeCardComponent {
  @Input() recipe!: Recipe;
  @Input() isLiked = false;

  @Output() isLikedChange = new EventEmitter<boolean>();
  @Output() onContext = new EventEmitter<[Recipe, MouseEvent]>();

  recipeIdentifier = '';

  constructor(private apiFitService: ApiFitService) {}

  ngOnInit() {
    this.recipeIdentifier =
      this.recipe.name.toLowerCase().replaceAll(' ', '-') +
      '-' +
      this.recipe.id;
    this.isLiked = this.recipe.isLiked || false;
  }

  handleContextMenu(ev: Event) {
    this.onContext.emit([this.recipe, ev as MouseEvent]);
  }

  toggleLike() {
    if (!this.recipe) return;

    let request;

    if (this.isLiked) {
      request = this.apiFitService.unlikeRecipe({ recipeId: this.recipe.id });
    } else {
      request = this.apiFitService.likeRecipe({ recipeId: this.recipe.id });
    }

    request.subscribe({
      next: () => {
        this.isLiked = !this.isLiked;

        this.isLikedChange.emit(this.isLiked);
      },
    });
  }
}
