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-update-application',
  templateUrl: './update-application.component.html',
  styleUrls: ['./update-application.component.scss']
})
export class UpdateApplicationComponent implements OnInit {
  application?: Application;
  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 _modalService: ModalService,
    private _applicationService: ApplicationService,
    private _referentialDataService: ReferentialDataService
  ) {}

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

    this.application = this._modalService.data;
    this.form.controls.name.setValue(this.application?.name);
    this.form.controls.serviceName.setValue(this.application?.serviceName);
    this.form.controls.serviceType.setValue(this.application?.serviceType);
    this.form.controls.image.setValue(this.application?.image);
  }

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

  onSubmit(): void {
    if (this.form.valid) {
      const appToUpdate = { ...this.application } as Application;
      appToUpdate.name = this.form.controls.name.value;
      appToUpdate.serviceName = this.form.controls.serviceName.value;
      appToUpdate.serviceType = this.form.controls.serviceType.value;
      appToUpdate.image = this.form.controls.image.value;

      this._applicationService.update(appToUpdate)
          .then(() => {
            console.log('Application uodated.');
            this._modalService.close();
          })
          .catch(error => console.error('An error occured while updating the application.'));
    } else {
      console.error('Form is invalid');
    }
  }

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