import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { Observable, of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { IRouterModel } from '@fleio-api/openstack/model/router.model';
import { RoutersApiService } from '@fleio-api/openstack/routers/routers-api.service';
import { IRouterCreateOptionsModel } from '@fleio-api/openstack/model/router-create-options.model';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { NotificationService } from '@shared/ui-api/notification.service';

@Component({
  selector: 'app-router-edit-form',
  templateUrl: './router-edit-form.component.html',
  styleUrls: ['./router-edit-form.component.scss']
})
export class RouterEditFormComponent extends DetailsFormBase<IRouterModel> implements OnInit {
  routerForm = this.formBuilder.group({
    region: ['', Validators.required],
    name: ['', Validators.required],
    description: [''],
    external_network_id: [''],
    admin_state_up: ['true'],
  });

  clientSelection: boolean;
  createInClientProject = true;

  createOptions: IRouterCreateOptionsModel;
  externalNetworks: {
    name: string;
    id: string;
    region: string;
  }[];

  constructor(
    private formBuilder: UntypedFormBuilder,
    private routersApiService: RoutersApiService,
    private router: Router,
    private config: ConfigService,
    private notificationService: NotificationService,
  ) {
    super();
  }

  changeDestination(value) {
    // createInClientProject
    if (value === false) {
      this.routerForm.controls.client.setValue('');
      this.routerForm.controls.client.clearValidators();
      this.routerForm.controls.client.reset();
    } else {
      this.routerForm.controls.client.setValidators(Validators.required);
    }
  }


  ngOnInit() {
    super.ngOnInit();
    this.clientSelection = this.config.authService.feature('ui.openstack.routers.create.client-select');
    if (this.objectController) {
      this.objectController.actionCallback = () => this.routerActions();
      this.createOptions = this.objectController.additionalObjects.createOptions;
    }

    if (this.createOptions && this.createOptions.availability_zones &&
      this.config.authService.feature('openstack.routers.availability_zones') &&
      this.createOptions.availability_zones.length && !this.object?.id) {
      this.routerForm.addControl('availability_zone_hints', this.formBuilder.control([]));
    }

    if (this.clientSelection) {
      this.routerForm.addControl('client', this.formBuilder.control('', Validators.required));
    }
    if (this.object && this.object.id) {
      this.routerForm.patchValue(this.object);
      if (this.routerForm.contains('client')) {
        this.routerForm.controls.client.disable();
      }
      this.routerForm.controls.region.disable();
      this.routerForm.controls.external_network_id.disable();
    }

    this.routerForm.controls.region.valueChanges.subscribe(region => {
      this.externalNetworks = [];
      if (region) {
        this.externalNetworks = this.createOptions.external_networks.filter(net => net.region === region);
      }
    });

    if (this.createOptions.regions && this.createOptions.regions.length && !this.object.id) {
      this.routerForm.controls.region.setValue(this.createOptions.selected_region);
    }
  }

  routerActions(): Observable<IActionResult> {
    const value = this.routerForm.value as any;

    if (this.clientSelection && value.client && (value.client as IClientModel).id) {
      value.client = (value.client as IClientModel).id;
    }

    if (!this.object.id && !this.createInClientProject) {
      value.create_as_admin = true;
    }

    this.createOrUpdate(
      this.routersApiService,
      value,
    ).subscribe(response => {
      this.redirectAfterCreate('openstack/routers', this.router, this.config);
      this.notificationService.showMessage($localize`Router saved`);
    });
    return of(null);
  }
}
