import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormArray, UntypedFormBuilder, Validators } from '@angular/forms';
import { NotificationService } from '@shared/ui-api/notification.service';
import { of } from 'rxjs';
import { IRouterModel } from '@fleio-api/openstack/model/router.model';
import { RoutersApiService } from '@fleio-api/openstack/routers/routers-api.service';

@Component({
  selector: 'app-router-static-routes-form',
  templateUrl: './router-static-routes-form.component.html',
  styleUrl: './router-static-routes-form.component.scss'
})
export class RouterStaticRoutesFormComponent extends DetailsFormBase<IRouterModel> implements OnInit {
  staticRoutesForm = this.formBuilder.group({
    routes: this.formBuilder.array([]),
  });

  staticRoutes: UntypedFormArray = this.staticRoutesForm.controls.routes as UntypedFormArray;

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

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.saveRoutes();
    }
    if (this.object) {
      for (const staticRoute of this.object.routes) {
        this.addRoute(staticRoute.destination, staticRoute.nexthop);
      }
    }
  }

  addRoute(destination: string = '', nexthop: string = '') {
    this.staticRoutes.push(
      this.formBuilder.group({
        destination: [destination, Validators.required],
        nexthop: [nexthop, Validators.required],
      })
    );
  }

  saveRoutes() {
    this.validate();
    if (this.formGroup.invalid) {
      this.displayControlErrors();
      return;
    }
    const router = {...this.object};
    router.routes = this.staticRoutes.value;

    this.objectController.loading = true;
    this.routersApiService.update(router.id, {routes: router.routes} as any).subscribe({
        next: () => {
          this.notificationService.showMessage($localize`Static routes updated`);
        }, error: (error) => {
          if (error.error) {
            this.setErrors(error.error);
          }
        }
      }
    ).add(() => {
      this.objectController.loading = false;
    });
    return of(null);
  }

  deleteRoute(index: number) {
    this.staticRoutes.removeAt(index);
  }
}
