import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { IDomainRegistrarModel } from '@fleio-api/plugins/domains/model/domain-registrar.model';
import { DomainRegistrarsApiService } from '@fleio-api/plugins/domains/domain-registrars-api.service';
import { RegistrarConnectorApiService } from '@fleio-api/plugins/domains/registrar-connector-api.service';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';

@Component({
  selector: 'app-registrar-edit-form',
  templateUrl: './registrar-edit-form.component.html',
  styleUrls: ['./registrar-edit-form.component.scss']
})
export class RegistrarEditFormComponent extends DetailsFormBase<IDomainRegistrarModel> implements OnInit {
  registrarFrom = this.formBuilder.group({
    name: ['', Validators.required],
    connector: ['', Validators.required],
  });
  connectorPlaceholderUnselected = $localize`Select registrar connector ...`;
  connectorPlaceholderSelected = $localize`Registrar connector`;

  constructor(
    private router: Router,
    private formBuilder: UntypedFormBuilder,
    private config: ConfigService,
    private domainRegistrarsApiService: DomainRegistrarsApiService,
    public registrarConnectorApiService: RegistrarConnectorApiService,
  ) {
    super();
  }

  ngOnInit() {
    super.ngOnInit();

    if (this.objectController) {
      this.objectController.actionCallback = () => this.registrarActions();
    }

    if (this.object) {
      this.registrarFrom.patchValue(this.object);
      this.registrarFrom.controls.connector.setValue({
        id: this.object.connector,
        name: this.object.registrar_connector_display,
      });
    }
  }

  registrarActions(): Observable<IActionResult> {
    const value = this.registrarFrom.value as IDomainRegistrarModel;
    if (value.connector instanceof Object) {
      if (value.connector.id) {
        value.connector = value.connector.id;
      } else {
        value.connector = null;
      }
    }
    this.createOrUpdate(
      this.domainRegistrarsApiService,
      value,
    ).subscribe(() => {
      this.router.navigateByUrl(
        this.config.getPrevUrl('domains/registrars')
      ).catch(() => {
      });
    });

    return of(null);
  }
}
