import { Component, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { InputTextModule } from 'primeng/inputtext';
import { CheckboxModule } from 'primeng/checkbox';
import { ButtonModule } from 'primeng/button';
import { CardModule } from 'primeng/card';
import { DividerModule } from 'primeng/divider';
import { ProgressBarModule } from 'primeng/progressbar';

@Component({
  selector: 'app-knock-page',
  standalone: true,
  imports: [
    CommonModule, RouterModule, ReactiveFormsModule,
    InputTextModule, CheckboxModule, ButtonModule, CardModule,
    DividerModule, ProgressBarModule
  ],
  templateUrl: './knock-page.component.html',
  styleUrls: ['./knock-page.component.scss']
})
export class KnockPageComponent {
  private readonly http = inject(HttpClient);
  private readonly fb = inject(FormBuilder);

  executing = false;
  elapsedMs = 0;
  private timerId: any = null;
  private startTs = 0;

  result: string | null = null;
  error: string | null = null;

  form = this.fb.group({
    targets: ['tcp:127.0.0.1:22', Validators.required],
    delay: ['1s', Validators.required],
    waitConnection: [false]
  });

  execute() {
    this.error = null;
    this.result = null;
    if (this.form.invalid) return;

    const v = this.form.value;
    const body: any = {
      targets: v.targets,
      delay: v.delay,
      waitConnection: v.waitConnection
    };

    this.executing = true;
    this.startTimer();

    // Без обязательного Basic-Auth: заголовок не добавляется, если пароль не требуется
    this.http.post('/api/v1/knock-actions/execute', body).subscribe({
      next: () => {
        this.executing = false;
        this.stopTimer();
        this.result = `Done in ${(this.elapsedMs / 1000).toFixed(2)}s`;
      },
      error: (e: HttpErrorResponse) => {
        this.executing = false;
        this.stopTimer();
        this.error = (e.error?.error) || e.message;
      }
    });
  }

  private startTimer() {
    this.elapsedMs = 0;
    this.startTs = Date.now();
    this.clearTimer();
    this.timerId = setInterval(() => {
      this.elapsedMs = Date.now() - this.startTs;
    }, 100);
  }

  private stopTimer() {
    if (this.startTs > 0) {
      this.elapsedMs = Date.now() - this.startTs;
    }
    this.clearTimer();
  }

  private clearTimer() {
    if (this.timerId) {
      clearInterval(this.timerId);
      this.timerId = null;
    }
  }
}


