import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Application } from 'src/app/core/entities/Application';
import { ReferentialData } from 'src/app/core/entities/ReferentialData';
import { ApplicationService } from 'src/app/core/services/application.service';
import { ModalService } from 'src/app/core/services/modal.service';
import { ReferentialDataService } from 'src/app/core/services/referential-data.service';

@Component({
  selector: 'app-create-application',
  templateUrl: './create-application.component.html',
  styleUrls: ['./create-application.component.scss']
})
export class CreateApplicationComponent implements OnInit {
  form: FormGroup = this._formBuilder.group({
    name: [undefined, Validators.required],
    serviceName: [undefined, Validators.required],
    serviceType: [undefined, Validators.required],
    image: [undefined, Validators.required]
  });
  serviceTypes: ReferentialData[] = [];

  constructor(
    private _formBuilder: FormBuilder,
    private _referentialDataService: ReferentialDataService,
    private _applicationService: ApplicationService,
    private _modalService: ModalService
  ) { }

  ngOnInit(): void {
    this._referentialDataService.getServiceTypes()
        .then(serviceTypes => this.serviceTypes = serviceTypes)
        .catch(error => console.error('An error occured while loading service types.'));
  }

  onServiceTypeSelection(event: ReferentialData): void {
    this.form.controls.serviceType.setValue(event.value);
    console.log(event.value);
  }

  onSubmit(): void {
    if (this.form.valid) {
      const appToAdd: Application = this.form.value as Application;
      this._applicationService.add(appToAdd)
          .then(applicationAdded => {
            console.log('Application added.');
            this._modalService.close();
          })
          .catch(error => console.error('An error occured while adding the new application.'));
    } else {
      console.error('Form is invalid');
    }
  }

  onCancel(): void {
    this._modalService.close();
  }
}
