package ru.themixray.repeating_mod;

import ru.themixray.repeating_mod.widget.RecordListWidget;

import java.io.File;
import java.nio.file.Files;
import java.util.*;

public class RecordList {
    private final File folder;
    private LinkedList<RecordState> records;
    private RecordListWidget widget;

    public RecordList(File folder) {
        this.folder = folder;
        this.records = new LinkedList<>();
        this.widget = new RecordListWidget(0, 0, 180, 200);
    }

    public List<RecordState> getRecords() {
        return records;
    }

    public File getFolder() {
        return folder;
    }

    public RecordListWidget getWidget() {
        return widget;
    }

    public void loadRecords() {
        LinkedList<File> files = new LinkedList<>(List.of(folder.listFiles()));

        files.sort(Comparator.comparingLong((f) -> f.lastModified()));

        for (File file : files) {
            try {
                addRecord(file);
            } catch (Exception e) {}
        }
    }

    public RecordState addRecord(File file) throws Exception {
        RecordState st = RecordState.load(file);
        addRecord(st);
        return st;
    }

    public void addRecord(RecordState record) {
        if (record == null) return;
        records.add(record);
        widget.addWidget(record);
    }

    public void removeRecord(RecordState record) {
        records.remove(record);
        widget.removeWidget(record);
    }

    public RecordState newRecord() {
        Date date = new Date();
        String name = "Unnamed";
        String author = Main.client.player.getName().getString();

        File file = new File(Main.me.records_folder,
            "record_" + RecordState.FILE_DATE_FORMAT.format(date) +
                "_" + Main.rand.nextInt(10) + ".rrm");

        RecordState state = new RecordState(
                file, name, date, author,
                new ArrayList<>(),
                null,
                null);

        addRecord(state);

        return state;
    }

    public RecordState cloneRecord(File file) throws Exception {
        File out = new File(Main.me.records_folder, file.getName());
        Files.copy(file.toPath(), out.toPath());
        RecordState state = RecordState.load(out);
        addRecord(state);
        return state;
    }
}
