import { Component } from '@angular/core';
import {Observable} from "rxjs";
import {HttpClient} from "@angular/common/http";
import {RouterLink} from "@angular/router";

@Component({
  selector: 'app-api-python',
  standalone: true,
  imports: [
    RouterLink
  ],
  templateUrl: './api-python.component.html',
  styleUrl: './api-python.component.css'
})
export class ApiPythonComponent {

  pythonScript!: string;
  pythonUsage!: string;

  ngOnInit(): void {
    this.getPythonScript().subscribe(
      data => this.pythonScript = data,
      error => console.error(error)
    );

    this.getPythonScriptUsage().subscribe(
      data => this.pythonUsage = data,
      error => console.error(error)
    );
  }

  constructor(private http: HttpClient) { }

  getPythonScript(): Observable<string> {
    return this.http.get('/assets/nise.py', { responseType: 'text' });
  }

  getPythonScriptUsage(): Observable<string> {
    return this.http.get('/assets/nise_usage.py', { responseType: 'text' });
  }


  copyToClipboard(): void {
    navigator.clipboard.writeText(this.pythonScript)
      .then(() => alert('Copied to clipboard!'))
      .catch(() => alert('Failed to copy to clipboard!'));
  }

  download(): void {
    const blob = new Blob([this.pythonScript], {type: 'text/plain'});
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'nise.py';
    a.click();
    window.URL.revokeObjectURL(url);
  }

}
