import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { IBaseFleioObjectModel } from '@fleio-api/base-model/base-fleio-object.model';
import { IPluginComponent } from '@shared/plugins/interfaces/plugin-component';
import { UntypedFormBuilder } from '@angular/forms';
import { SelectedExistingDomainService } from '@shared/plugins/common-tabs/domains/domains-select-domain/selected-existing-domain.service';
import { Observable, of } from 'rxjs';

@Component({
  selector: 'app-select-existing-domain',
  templateUrl: './select-existing-domain.component.html',
  styleUrls: ['./select-existing-domain.component.scss']
})
export class SelectExistingDomainComponent extends DetailsFormBase<IBaseFleioObjectModel> implements OnInit, IPluginComponent {
  selectExistingDomainForm = this.formBuilder.group({
    selected: ['']
  });
  public data: {
    existing_domains: Array<{name: string}>;
  };
  domainSelectedPlaceholder = $localize`Domain`;
  domainUnselectedPlaceholder = $localize`Select domain ...`;
  domainOptionsSwitchMap: (search: string) => Observable<any>;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private selectedExistingDomainService: SelectedExistingDomainService,
  ) {
    super();
  }

  ngOnInit(): void {
    this.domainOptionsSwitchMap = (search) => {
      const lowerCaseValue = search.toLocaleLowerCase();
      return of(this.data?.existing_domains?.filter(
        domain => domain.name.toLocaleLowerCase().includes(lowerCaseValue)
      ));
    };
    this.selectExistingDomainForm.controls.selected.valueChanges.subscribe(value => {
      if (value && value.name) {
        this.selectedExistingDomainService.setValue(value.name);
      } else {
        this.selectedExistingDomainService.setValue('');
      }
    });
  }

}
