import MediaLibraryDescriptor from "../descriptor/MediaLibraryDescriptor.js";
import MediaProfile from "../profile/MediaProfile.js";

export default class MediaPlaylistDescriptorLoader {
    /**
     * @param {FileSystemDirectoryHandle} rootFolderHandler 
     * @returns {Promise<MediaLibraryDescriptor>}
     */
    static async loadDescriptors(rootFolderHandler) {
        const mediaLibrary = new MediaLibraryDescriptor();

        try {
            const mediaDescriptorHandler = await rootFolderHandler.getFileHandle("media_library.json", { create: true });
            const descriptorFile = await mediaDescriptorHandler.getFile();
            const descriptionFileContent = await descriptorFile.text();

            if (descriptionFileContent == null || descriptionFileContent.length < 10) {
                return mediaLibrary;
            }

            const mediaDescriptorObj = JSON.parse(descriptionFileContent);

            if (mediaDescriptorObj != null && mediaDescriptorObj.name != null) {
                mediaLibrary.name = mediaDescriptorObj.name;
            }

            if (mediaDescriptorObj != null && mediaDescriptorObj.description != null) {
                mediaLibrary.description = mediaDescriptorObj.description;
            }

            if (mediaDescriptorObj != null && mediaDescriptorObj.root != null) {
                mediaLibrary.root = mediaDescriptorObj.root;
            }

            if (mediaDescriptorObj != null && mediaDescriptorObj.profiles != null) {
                mediaDescriptorObj.profiles.forEach(d => {
                    mediaLibrary.profiles.push(MediaProfile.fromJson(d));
                });
            }
        } catch (error) {
            return mediaLibrary;
        }

        return mediaLibrary;
    }
}