import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { IConfigOptionModel } from '@fleio-api/billing/model/config-option.model';
import { ConfigService } from '@shared/config/config.service';

@Component({
  selector: 'app-configurable-option-input',
  templateUrl: './configurable-option-input.component.html',
  styleUrls: ['./configurable-option-input.component.scss']
})
export class ConfigurableOptionInputComponent implements OnInit {
  @Input() option: IConfigOptionModel;
  @Input() value: string;
  @Input() error: string;
  @Output() valueChange = new EventEmitter<string>();

  constructor(public config: ConfigService) {
  }

  ngOnInit() {
    if (this.option?.widget === 'yesno') {
      // init default value for 'yesno' conf. opts.
      if (this.value === null) {
        this.value = 'no';
      }
      this.emitValueChange(this.value);
    }
  }

  emitValueChange(newValue: string) {
    if (newValue === '') {
      // blank is never allowed, send null so errors won't be triggered by DRF but by our custom validation
      newValue = null;
    }
    this.value = newValue;
    this.valueChange.emit(this.value);
    this.error = null;
  }
}
