import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Observable, Subscription } from 'rxjs';
import { AuthService } from 'src/app/auth/services/auth.service';
import { Stock } from 'src/app/models/sale-product.model';
import { ProductService } from 'src/app/services/product.service';

@Component({
  selector: 'app-data-delivery',
  templateUrl: './data-delivery.component.html',
  styleUrls: ['./data-delivery.component.scss']
})
export class DataDeliveryComponent implements OnInit, OnDestroy {
  @Input() idProduct: number;
  @Input() quantity: number;
  stock$: Observable<Stock[]>;
  subscriptionStock: Subscription;
  public data: any = {
    deliveryType: null,
    store: null,
    stockStore: null,
    quantity: 1
  };
  form: FormGroup;

  constructor(private readonly productService: ProductService,
    private readonly authService: AuthService
   ) { }

  ngOnDestroy(): void {
    if (this.subscriptionStock) {
      this.subscriptionStock.unsubscribe();
    }
  }

  ngOnInit(): void {
    this.stock$ = this.productService.getStocks(this.authService.getStore(), this.idProduct);
    this.data.quantity = this.quantity;
    this.data.store = '';
    this.data.deliveryType = '';
    this.data.stockStore = 0;
    this.form = new FormGroup({
      deliveryType: new FormControl(this.data.deliveryType, [
        Validators.required,
      ]),
      quantity: new FormControl(this.data.quantity, [
        Validators.required]),
        store: new FormControl(this.data.store, [Validators.required]),
        stockStore: new FormControl(this.data.stockStore, [Validators.required]),
        auxDescription: new FormControl(),
    });
    this.subscriptionStock = this.stock$.subscribe(stocks => {
      stocks.filter(stock => stock.quantity > 0)
            .sort(s => s.quantity * (-1))
            .forEach(stock => {
              this.form.patchValue({store: stock.store, stockStore: stock.quantity});
      });
    });
  }

  updateStockStore(store: any) {
    this.form.patchValue({stockStore: store.quantity});
  }

}
