package land.chipmunk.chipmunkmod.song;

import land.chipmunk.chipmunkmod.modules.SongPlayer;
import land.chipmunk.chipmunkmod.util.DownloadUtilities;
import net.minecraft.network.chat.Component;
import java.io.File;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class SongLoaderThread extends Thread {
    public SongLoaderException exception;
    public Song song;
    private String location;
    private File songPath;
    private URL songUrl;
    private final boolean isUrl;

    public SongLoaderThread (final URL location) throws SongLoaderException {
        isUrl = true;
        songUrl = location;
    }

    public SongLoaderThread (final Path location) throws SongLoaderException {
        isUrl = false;
        songPath = location.toFile();
    }

    public void run () {
        final byte[] bytes;
        final String name;
        try {
            if (isUrl) {
                bytes = DownloadUtilities.DownloadToByteArray(songUrl);
                name = Paths.get(songUrl.toURI().getPath()).getFileName().toString();
            } else {
                bytes = Files.readAllBytes(songPath.toPath());
                name = songPath.getName();
            }
        } catch (final Exception e) {
            exception = new SongLoaderException(Component.literal(e.getMessage()), e);
            return;
        }

        try {
            song = MidiConverter.getSongFromBytes(bytes, name);
        } catch (final Exception e) {
        }

        if (song == null) {
            try {
                song = NBSConverter.getSongFromBytes(bytes, name);
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }

        if (song == null) {
            exception = new SongLoaderException(Component.translatable("Invalid song format"));
        }
    }

    private File getSongFile (final String name) {
        return new File(SongPlayer.SONG_DIR, name);
    }
}
