import { ChangeDetectionStrategy, Component, EventEmitter, OnInit, Output } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { DomainOmsService } from '@domain/oms';
import { VATDTO } from '@swagger/oms';
import { Observable, Subscription } from 'rxjs';
import { shareReplay } from 'rxjs/operators';

@Component({
  selector: 'page-purchasing-options-modal-price-input',
  templateUrl: 'purchasing-options-modal-price-input.component.html',
  styleUrls: ['purchasing-options-modal-price-input.component.scss'],
  providers: [FormBuilder],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PurchasingOptionsModalPriceInputComponent implements OnInit {
  control: FormGroup;

  vats$: Observable<VATDTO[]> = this._omsService.getVATs().pipe(shareReplay());

  @Output()
  priceChanged = new EventEmitter<number>();

  @Output()
  vatChanged = new EventEmitter<VATDTO>();

  private _subscriptions = new Subscription();

  constructor(private _omsService: DomainOmsService, private _fb: FormBuilder) {}

  ngOnInit() {
    this.initForm();
  }

  initForm() {
    const fb = this._fb;
    this.control = fb.group({
      price: fb.control(undefined, [Validators.required, Validators.pattern(/^\d+([\,]\d{1,2})?$/), Validators.max(99999)]),
      vat: fb.control(undefined, [Validators.required]),
    });

    this._subscriptions.add(
      this.control.get('price').valueChanges.subscribe((price) => this.priceChanged.emit(Number(String(price).replace(',', '.'))))
    );
    this._subscriptions.add(this.control.get('vat').valueChanges.subscribe(this.vatChanged));

    this.control.markAllAsTouched();
  }
}
