import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatCheckbox } from '@angular/material/checkbox';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';

@Component({
  selector: 'app-register-serial',
  templateUrl: './register-serial.component.html',
  styleUrls: ['./register-serial.component.css']
})
export class RegisterSerialComponent implements OnInit{

  public arrItemsForm: Array<number>;
  public formGroup: FormGroup;
  constructor(
    @Inject(MAT_DIALOG_DATA) public registerSerial: RegisterSerial,
    private _dialogReg: MatDialogRef<RegisterSerial>,
  ) {
    
    this.formGroup = new FormGroup({
      'SERIAL_0': new FormControl('', Validators.required),
      'IS_UNIQUE': new FormControl(false),
    })
    
    this.arrItemsForm = [];
    if (!registerSerial.arrModel.IS_UNIQUE) {
      for (let index = 1; index < registerSerial.numberItems; index++) {
        this.arrItemsForm.push(index);
        this.formGroup.addControl('SERIAL_'+index, new FormControl('', Validators.required));
      }
    }
    this.formGroup.setValue(registerSerial.arrModel);
  }


  ngOnInit(): void {
    this.formGroup.controls['IS_UNIQUE'].valueChanges.subscribe((result) => {
      if (result) {
        for (let index = 1; index < this.registerSerial.numberItems; index++) {
          this.formGroup.removeControl('SERIAL_'+index);
        }
        this.arrItemsForm = [];
      } else {
        this.arrItemsForm = [];
        for (let index = 1; index < this.registerSerial.numberItems; index++) {
          this.arrItemsForm.push(index);
          this.formGroup.addControl('SERIAL_'+index, new FormControl('', Validators.required));
        }
      }

      this.formGroup.updateValueAndValidity();
    });
  }

  public save() {
    this._dialogReg.close({
      numberItems: this.registerSerial.numberItems,
      arrModel: this.formGroup.value
    });
  }

  
}

export interface RegisterSerial {
  numberItems: number;
  arrModel: any;
}