import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { IPublicKeyModel } from '@fleio-api/public-key/model/public-key.model';
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 { PublicKeysApiService } from '@fleio-api/public-key/public-key-api.service';
import { ClipboardService } from '@shared/ui-api/clipboard.service';
import { CallbackAction } from '@objects-view/actions/callback-action';
import { IAction } from '@shared/ui/objects-view/interfaces/actions/action';

@Component({
  selector: 'app-ssh-key-edit-form',
  templateUrl: './ssh-key-edit-form.component.html',
  styleUrls: ['./ssh-key-edit-form.component.scss']
})
export class SshKeyEditFormComponent extends DetailsFormBase<IPublicKeyModel> implements OnInit {
  sshKeyForm = this.formBuilder.group({
    name: ['', Validators.required],
    public_key: ['', Validators.required],
    private_key: [''],
  });
  generatedKey: Record<string, unknown>;
  isEdit = false;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private publicKeysApiService: PublicKeysApiService,
    private router: Router,
    private config: ConfigService,
    public clipboard: ClipboardService,
  ) {
    super();
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = (action: CallbackAction) => this.keyActions(action);
    }
    if (this.object && this.object.id) {
      this.isEdit = true;
      this.sshKeyForm.patchValue(this.object);
    }
  }

  keyActions(action: IAction): Observable<IActionResult> {
    if (action.internalName === 'generateKey') {
      this.objectController.loading = true;
      this.publicKeysApiService.getGeneratedKeyPair().subscribe(key => {
        this.generatedKey = key;
        this.sshKeyForm.patchValue(key);
      }).add(() => {
        this.objectController.loading = false;
      });
      return of(null);
    }
    const value = this.sshKeyForm.value;

    this.createOrUpdate(
      this.publicKeysApiService,
      value,
    ).subscribe(() => {
      this.redirectAfterCreate('openstack/ssh-keys', this.router, this.config);
    });

    return of(null);
  }
}
