import {Component, Input, OnInit} from '@angular/core';
import {Recipe} from '../../classes/recipe';
import {CalculatorService} from '../../services/calculator.service';
import {ActivatedRoute, Router} from '@angular/router';
import {DatabaseService} from '../../services/database.service';
import {AuthService} from '../../services/auth.service';
import {BrewContextService} from '../../services/brew-context.service';

@Component({
  selector: 'app-recipe-ingredients',
  templateUrl: './recipe-ingredients.component.html',
  styleUrls: ['./recipe-ingredients.component.css']
})
export class RecipeIngredientsComponent implements OnInit {

  @Input() recipe: Recipe;

  iTypeMapping = {
    malt: 'malts',
    hop: 'hops',
    yeast: 'yeasts',
    misc: 'misc'
  };

  constructor(private brewContext: BrewContextService,
              private calcService: CalculatorService,
              private router: Router,
              private route: ActivatedRoute,
              private dbService: DatabaseService,
              public authService: AuthService) {

  }

  getIngredients(): Array<any> {
    const result = [];
    for (const malt of this.recipe.malts) {
      malt.itype = 'malt';
      result.push(malt);
    }
    for (const hop of this.recipe.hops) {
      hop.itype = 'hop';
      result.push(hop);
    }
    for (const yeast of this.recipe.yeasts) {
      yeast.itype = 'yeast';
      result.push(yeast);
    }
    for (const misc of this.recipe.misc) {
      misc.itype = 'misc';
      result.push(misc);
    }

    return result;
  }

  removeIngredient(ingredient: any) {
    const ingredients = this.recipe[this.iTypeMapping[ingredient.itype]];
    for (const idx in ingredients) {
      const ing = ingredients[idx];
      if (ing === ingredient) {
        ingredients.splice(idx, 1);
      }
    }

    this.calcService.recalculateRecipe(this.brewContext.recipe, this.brewContext.brewSetup);
  }

  recalculate() {
    this.calcService.recalculateRecipe(this.brewContext.recipe, this.brewContext.brewSetup);
  }

  getStep(type: string): number {
    if (type === 'malt') {
      return 0.1;
    } else {
  saveRecipe() {
    this.dbService.saveRecipe(this.brewContext.recipe).subscribe(
      recipe => {
        this.brewContext.recipe = recipe;
        this.router.navigate(['../../calculator', recipe._id], {relativeTo: this.route});
      }
    );
  }

  gotoBrewSteps() {
    const link = ['../../brew-steps'];
    if (this.authService.isAuthenticated()) {
      this.dbService.saveRecipe(this.brewContext.recipe).subscribe(
        recipe => {
          this.brewContext.recipe = recipe;
          this.brewContext.addRecipe(recipe);
        }
      );
    }
    if (this.brewContext.recipe._id) { link.push(this.brewContext.recipe._id); }
    this.router.navigate(link, {relativeTo: this.route});
  }

  ngOnInit() {
  }

}
      return 1;
    }
  }
