74 lines
2.1 KiB
TypeScript
74 lines
2.1 KiB
TypeScript
import { useState, useEffect } from "react";
|
|
import { useNavigate } from "react-router-dom";
|
|
import type { PlaylistNode } from "../types/interfaces";
|
|
import { parseXmlFile } from "../services/xmlService";
|
|
import { api } from "../services/api";
|
|
|
|
export const useXmlParser = () => {
|
|
const [playlists, setPlaylists] = useState<PlaylistNode[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
const navigate = useNavigate();
|
|
|
|
// Load playlist structure from the backend on mount (faster loading)
|
|
useEffect(() => {
|
|
const loadData = async () => {
|
|
try {
|
|
// Load just the structure first for faster initial load
|
|
const loadedPlaylists = await api.getPlaylistStructure();
|
|
setPlaylists(loadedPlaylists);
|
|
} catch (err) {
|
|
console.error("Error loading playlist structure from backend:", err);
|
|
// Fallback to full playlist data if structure endpoint fails
|
|
try {
|
|
const fullPlaylists = await api.getPlaylists();
|
|
setPlaylists(fullPlaylists);
|
|
} catch (fallbackErr) {
|
|
console.error("Error loading full playlists from backend:", fallbackErr);
|
|
}
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
loadData();
|
|
}, []);
|
|
|
|
const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
|
const file = event.target.files?.[0];
|
|
if (!file) return;
|
|
|
|
const reader = new FileReader();
|
|
reader.onload = async (e) => {
|
|
const xmlText = e.target?.result as string;
|
|
try {
|
|
const { songs: parsedSongs, playlists: parsedPlaylists } = await parseXmlFile(xmlText);
|
|
|
|
// Save to backend
|
|
await Promise.all([
|
|
api.saveSongs(parsedSongs),
|
|
api.savePlaylists(parsedPlaylists)
|
|
]);
|
|
|
|
// Navigate to home and refresh the page
|
|
navigate('/');
|
|
window.location.reload();
|
|
} catch (err) {
|
|
console.error("Error processing XML:", err);
|
|
}
|
|
};
|
|
reader.readAsText(file);
|
|
};
|
|
|
|
const resetLibrary = async () => {
|
|
setPlaylists([]);
|
|
setLoading(false);
|
|
};
|
|
|
|
return {
|
|
playlists,
|
|
setPlaylists,
|
|
handleFileUpload,
|
|
loading,
|
|
resetLibrary,
|
|
};
|
|
};
|