import css from "../css/main.css";
import MediaProfile from "./profile/MediaProfile.js";
import FSUtil from "./util/FSUtil.js";

async function load(){
    const dir = await showDirectoryPicker({"id": "mediaplayer_amin", "mode": "readwrite"});
    await walkFileTree(dir);
}

async function walkFileTree(currentDir){
    for await (const value of currentDir.values()) {
        if(value.kind == 'directory'){
            await walkFileTree(value);
        } else if(value.kind == 'file' && value.name == 'playlist.json'){
            await getVideo(currentDir, value);
        }
    }
}

async function getVideo(dir, playlistFile){
    const file = await playlistFile.getFile();
    console.log("Playlist file:", file);
    const content = await file.text();
    const playlist = JSON.parse(content);
    console.log(playlist);
    const videoPath = playlist.tracks[0].relativePath;
    console.log(videoPath);

    const videoHandle = await FSUtil.getFileHandle(dir, videoPath);
    console.log(videoHandle);
    playVideo(await videoHandle.getFile());
}

function playVideo(file){
    document.getElementById("video").src = URL.createObjectURL(file);
}

document.getElementById("startAppButton").addEventListener("click", load);