aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/net/sowgro/npehero/levelapi/Level.java
blob: 0e254452287aaf7c9383033924a13e8c2d0bb90b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package net.sowgro.npehero.levelapi;

import java.io.*;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javafx.scene.image.Image;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.paint.Color;

import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;

public class Level implements Comparable<Level>{

    public static final String SONG_FILE = "song";
    public static final String BACKGROUND_FILE = "background";
    public static final String PREVIEW_FILE = "preview";

    public final File dir;

    public String title = "Unnamed";
    public String artist = "Unknown";
    public String desc;
    public Color[] colors = {Color.RED,Color.BLUE,Color.GREEN,Color.PURPLE,Color.YELLOW};
    public Image preview;
    public Image background;
    public Media song;

    public Difficulties difficulties;

    private final File jsonFile;
    private final Gson jsonParser = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
    private File songFile;
    private File previewFile;
    private File backgroundFile;

    /**
     * Creates a new level
     * @param newDir The path of the Level
     * @throws IOException If there is a problem reading the metadata file or loading the difficulties
     */
    public Level(File newDir) throws IOException
    {
        dir = newDir;
        jsonFile = new File(dir, "metadata.json");
        readFiles();
        readMetadata();
        difficulties = new Difficulties(this);
    }

    /**
     * Check for a song file, background file and preview image file
     */
    public void readFiles() {
        songFile = null;
        previewFile = null;
        backgroundFile = null;
        song = null;
        background = null;
        preview = null;
        File[] fileList = dir.listFiles();
        if (fileList == null) {
            return;
        }
        for (File file : fileList) {
            String fileName = file.getName();
            if (fileName.contains(SONG_FILE)) {
                songFile = file;
                song = new Media(file.toURI().toString());
                new MediaPlayer(song); // allows song.getDuration() to return
            }
            else if (fileName.contains(BACKGROUND_FILE)) {
                backgroundFile = file;
                background = new Image(file.toURI().toString());
            }
            else if (fileName.contains(PREVIEW_FILE)) {
                previewFile = file;
                preview = new Image(file.toURI().toString());
            }
        }

    }

    /**
     * Read in metadata file
     * @throws IOException If there is a problem reading the file
     */
    public void readMetadata() throws IOException {
        if (!jsonFile.exists()) {
            return;
        }
        @SuppressWarnings("unchecked")
        Map<String, Object> data = jsonParser.fromJson(new FileReader(jsonFile), Map.class);
        if (data == null) {
            return;
        }
        title = (String) data.getOrDefault("title", title);
        artist = (String) data.getOrDefault("artist", artist);
        desc = (String) data.getOrDefault("desc", desc);
        colors[0] = Color.web((String) data.getOrDefault("color1", colors[0].toString()));
        colors[1] = Color.web((String) data.getOrDefault("color2", colors[1].toString()));
        colors[2] = Color.web((String) data.getOrDefault("color3", colors[2].toString()));
        colors[3] = Color.web((String) data.getOrDefault("color4", colors[3].toString()));
        colors[4] = Color.web((String) data.getOrDefault("color5", colors[4].toString()));
    }

    /**
     * Checks if the level is valid.
     * <p>
     * A valid level has a song file and 1 or more valid difficulties
     * @return True if the level is valid
     */
    public boolean isValid() {
        if (song == null) {
            return false;
        }

        if (difficulties.getValidList().isEmpty()) {
            return false;
        }
        return true;
    }

    /**
     * Writes metadata to json file
     * @throws IOException If there is a problem writing to the file.
     */
    public void writeMetadata() throws IOException {
        if (!jsonFile.exists() && !jsonFile.createNewFile()) {
            throw new IOException("Could not create file " + jsonFile.getAbsolutePath());
        }
        @SuppressWarnings("unchecked")
        Map<String, Object> data = jsonParser.fromJson(new FileReader(jsonFile), Map.class);
        if (data == null) {
            data = new HashMap<>();
        }
        data.put("title", title);
        data.put("artist", artist);
        data.put("desc", desc);
        data.put("color1",colors[0].toString());
        data.put("color2",colors[1].toString());
        data.put("color3",colors[2].toString());
        data.put("color4",colors[3].toString());
        data.put("color5",colors[4].toString());
        FileWriter fileWriter = new FileWriter(jsonFile);
        jsonParser.toJson(data, fileWriter);
        fileWriter.close();
    }


    /**
     * Copies a file into the level directory with the name provided. The extension will be inherited from the source file
     * @param source: the file to be copied
     * @param name: the new file name EXCLUDING the extension.
     * @throws IOException If there is a problem adding the file
     */
    public void addFile(File source, String name) throws IOException {
        name = name + "." + getFileExtension(source);
        Files.copy(source.toPath(), new File(dir, name).toPath(), StandardCopyOption.REPLACE_EXISTING);
        readFiles();
    }

    /**
     * Deletes a file from the level's directory
     * @param name the new file name EXCLUDING the extension.
     * @throws IOException If there is a problem deleting the file
     */
    public void removeFile(String name) throws IOException {
        File f = switch (name) {
            case SONG_FILE -> songFile;
            case BACKGROUND_FILE -> backgroundFile;
            case PREVIEW_FILE -> previewFile;
            default -> throw new IllegalArgumentException("Invalid file name " + name);
        };
        if (!f.delete()) {
            throw new IOException("Failed to delete file " + f.getAbsolutePath());
        }
        readFiles();
    }

    @Override
    public int compareTo(Level other) {
        return title.compareTo(other.title);
    }

    /**
     * Get the extension of a file.
     * @param file The file to return the extension of
     * @return The extension of the file in the format "*.ext"
     */
    public String getFileExtension(File file) {
        return file.getName().substring(file.getName().lastIndexOf('.') + 1);
    }
}