package leigh.m3;

import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.function.Consumer;

/**
 * This class implements a media repository which stores a total collection of media files which are available
 * for streaming. It also contains the shuffle mechanic which randomizes the order the files are to be played in.
 *
 * @author Alex Leigh
 */
public class MediaRepository {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(MediaRepository.class);
    private final Path base;
    private ArrayList<M3U> files;

    public MediaRepository(Path base) {
        this.base = base;
    }

    /**
     * Return a shuffled list of all the files in this repo.
     */
    public ArrayList<M3U> getFiles() {
        Collections.shuffle(files);
        return files;
    }

    /**
     * Scan the base path for all <code>.m3u8</code> files. Each file found will be loaded into this repo.
     */
    public void scan() throws IOException {
        ArrayList<M3U> files = new ArrayList<>();

        Files.walk(base).forEach(new Consumer<Path>() {
            @Override
            public void accept(Path path) {
                logger.debug("Evaluating. [path: {}]", path);
                if(path.toFile().isFile() && path.toString().endsWith(".m3u8")) {
                    try {
                        files.add(new M3U(path));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        logger.info("Rescanned media folder. [count: {}]", files.size());

        this.files = files;
    }
}
