import { ChangeDetectionStrategy, Component, inject, input } from '@angular/core';
import { TuiButton } from '@taiga-ui/core/components/button';

import { UserErrorNotifyService } from '../../../../core/notifications/user-error-notify.service';
import { SessionsApiService } from '../../../../core/services/sessions-api.service';
import type { SessionDetailResponse, StreamInfo } from '../../../../core/models/api.types';
import { formatDurationMsHuman } from '../../../../shared/utils/duration.util';
import type { TelemetryLoadState } from '../session-detail.types';

@Component({
  selector: 'app-session-info-tab',
  imports: [TuiButton],
  templateUrl: './session-info-tab.html',
  styleUrl: './session-info-tab.css',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SessionInfoTabComponent {
  private readonly api = inject(SessionsApiService);
  private readonly userErrors = inject(UserErrorNotifyService);

  readonly detail = input.required<SessionDetailResponse>();
  readonly telemetryState = input.required<TelemetryLoadState>();

  protected formatDurationMs(ms: number | null | undefined): string {
    return formatDurationMsHuman(ms);
  }

  protected streamResolvedPlaylistUrl(stream: StreamInfo): string {
    return this.api.resolvePlaylistUrl(stream.playlist_url);
  }

  protected async copyDetailPayloadJson(): Promise<void> {
    const text = this.detailPayloadJson();
    try {
      await navigator.clipboard.writeText(text);
      this.userErrors.notifySuccess('JSON сессии скопирован в буфер обмена.', 'Готово');
    } catch {
      // clipboard
    }
  }

  private detailPayloadJson(): string {
    try {
      return JSON.stringify(this.detail(), null, 2);
    } catch {
      return '{}';
    }
  }
}
