import { Component, OnInit, Input, Output, EventEmitter, OnChanges } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Observable, of, switchMap } from 'rxjs';

import { Product } from '../product';

import { ProductsService } from '../products.service';
import { AuthService } from '../../auth/auth.service';
import { CartService } from '../../cart/cart.service';

@Component({
  selector: 'app-product-detail',
  templateUrl: './product-detail.component.html',
  styleUrls: ['./product-detail.component.css']
})
export class ProductDetailComponent implements OnInit, OnChanges {

  @Input() product: Product | undefined;
  @Output() bought = new EventEmitter();
  @Input() id = -1;
  product$: Observable<Product> | undefined;
  @Output() deleted = new EventEmitter();
  price: number | undefined;

  ngOnChanges(): void {
    this.product$ = this.productService.getProduct(this.id);
    console.log(this.id)
    }

    buy(product: Product) {
      this.cartService.addProduct(product);
   }


  constructor(
    private productService: ProductsService,
    public authService: AuthService,
    private route: ActivatedRoute,
    private cartService: CartService
 ) { }


  changePrice(product: Product, price: number) {
    this.productService.updateProduct(product.id, price).subscribe(()=> {
       alert('Cena '+ product.name + ' się zmieniła!');
    });
 }

 remove(product: Product) {
  this.productService.deleteProduct(product.id).subscribe(() => {
     this.deleted.emit();
  });
}

ngOnInit(): void {
  this.product$ = this.route.data.pipe(
     switchMap(data => of(data['product']))
  );
}



}
