import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Song } from '../models/song'; import { parseString } from 'xml2js'; import { Riff } from '../models/riff'; @Injectable({ providedIn: 'root' }) export class SongService { apiUrl = 'http://localhost:8080/song'; private pdfUrl = 'http://localhost:8080/pdf'; constructor(private http: HttpClient) {} getAllSongs(): Observable { return this.http.get(this.apiUrl); } uploadSong(song: Song): Observable { const headers = new HttpHeaders({ 'Content-Type': 'application/json' }); return this.http.post(this.apiUrl, song, { headers }); } parseXmlToSong(xmlContent: string): Observable { return new Observable((observer) => { parseString(xmlContent, (err, result) => { if (err) { observer.error(err); } else { const track = result.Track; const name = track.Name[0]; const riffsXml = track.Riffs[0].Riff; const riffs = riffsXml.map((riffXml: any) => { return new Riff( 0, riffXml.Name[0], riffXml.StartMs[0], riffXml.EndMs[0], riffXml.GroupColor[0] ); }); const song = new Song(0, name, '', riffs, 0, 0, 0, new Date(), new Date()); observer.next(song); observer.complete(); } }); }); } generateXaml(song: Song): string { const songXml = this.songToXml(song); const xaml = `${songXml}`; return xaml; } songToXml(song: Song): string { const xmlBuilder = require('xmlbuilder'); const songXml = xmlBuilder.create('Track', { version: '1.0', encoding: 'UTF-8' }); if (song.riffs && song.riffs.length > 0) { const riffsXml = songXml.ele('Riffs'); for (const riff of song.riffs) { const riffXml = riffsXml.ele('Riff'); riffXml.ele('Name', riff.name); riffXml.ele('StartMs', riff.startMs); riffXml.ele('EndMs', riff.endMs); riffXml.ele('GroupColor', riff.groupColor); riffXml.up(); } } songXml.ele('Name', song.name); return songXml.end({ pretty: true }); } // generatePdf(songId: number): void { // this.http.get(`${this.pdfUrl}/${songId}`, { responseType: 'blob' }).subscribe( // (response: Blob) => { // const filename = 'song.pdf'; // Provide a default filename // const blob = new Blob([response], { type: 'application/pdf' }); // this.downloadFile(blob, filename); // }, // (error: any) => { // console.error('Error generating PDF:', error); // // Handle error if needed // } // ); // } // // // downloadFile(blob: Blob, filename: string): void { // const anchorElement = document.createElement('a'); // anchorElement.href = window.URL.createObjectURL(blob); // anchorElement.download = filename; // anchorElement.click(); // window.URL.revokeObjectURL(anchorElement.href); // } generatePdf(songId: number): Observable { return this.http.get(`${this.pdfUrl}/${songId}`, { responseType: 'blob' }); } }