import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { map } from 'rxjs/operators';
import { ChangePizzaDto, CreatePizzaGQL, ListToppingsForPizzaCreateGQL, Topping, ToppingChangedGQL } from 'src/generated/graphql';
import { MatSnackBar } from '@angular/material/snack-bar';

@Component({
  selector: 'app-pizza-create',
  templateUrl: './pizza-create.component.html',
  styleUrls: ['./pizza-create.component.scss']
})
export class PizzaCreateComponent implements OnInit {


  pizzaName = new FormControl('');
  pizzaToppings = new FormControl([]);
  pizzaCreateForm = new FormGroup({
    pizzaName: this.pizzaName,
    pizzaToppings: this.pizzaToppings,
  });

  toppings: Topping[];

  create(): void {
    if (!this.pizzaCreateForm.valid) {
      return;
    }
    const createPizzaDto: ChangePizzaDto = {
      name: this.pizzaName.value,
      toppingIds: this.pizzaToppings.value.map((topping: Topping) => topping.id)
    };
    this.createPizza
      .mutate({ createPizzaDto })
      .subscribe((res) => {
        this.snackBar.open(
          `created Pizza ${res.data.createPizza.name}`,
          'ok',
          {
            duration: 1000
          }
        );
      });
    this.pizzaName.setValue(null);
    this.pizzaToppings.setValue([]);
  }

  ngOnInit(): void {
  }

  constructor(
    listToppings: ListToppingsForPizzaCreateGQL,
    protected createPizza: CreatePizzaGQL,
    toppingChanged: ToppingChangedGQL,
    private snackBar: MatSnackBar
  ) {
    listToppings
      .watch()
      .valueChanges
      .pipe(map(result => result.data.listTopping as Topping[]))
      .subscribe(toppings => this.toppings = toppings);
    toppingChanged
      .subscribe()
      .pipe(map(event => event.data.toppingsChanged as Topping[]))
      .subscribe(toppings => this.toppings = toppings);
  }



}
