summaryrefslogtreewikicommitdiff
path: root/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java
blob: 5e28258a5b48753db4c509c2a9d2e74861474ca2 (plain)
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/*
 * This file is part of Kenshins Hide and Seek
 *
 * Copyright (c) 2021 Tyler Murphy.
 *
 * Kenshins Hide and Seek free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * he Free Software Foundation version 3.
 *
 * Kenshins Hide and Seek is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

package net.tylermurphy.hideAndSeek.configuration;

import net.tylermurphy.hideAndSeek.Main;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

public class ConfigManager {

    private final File file;
    private YamlConfiguration config,defaultConfig;
    private String defaultFilename;

    public static ConfigManager create(String filename) {
        return new ConfigManager(filename, filename);
    }

    public static ConfigManager create(String filename, String defaultFilename) {
        return new ConfigManager(filename, defaultFilename);
    }

    private ConfigManager(String filename, String defaultFilename) {

        File dataFolder = Main.getInstance().getDataFolder();
        File oldDataFolder = new File(Main.getInstance().getDataFolder().getParent() + File.separator + "HideAndSeek");

        this.defaultFilename = defaultFilename;
        this.file = new File(dataFolder, filename);

        if(oldDataFolder.exists()){
            if(!dataFolder.exists()){
                if(!oldDataFolder.renameTo(dataFolder)){
                    throw new RuntimeException("Could not rename folder: " + oldDataFolder.getPath());
                }
            } else {
                throw new RuntimeException("Plugin folders for HideAndSeek & KenshinsHideAndSeek both exists. There can only be one!");
            }

        }

        if (!dataFolder.exists()) {
            if (!dataFolder.mkdirs()) {
                throw new RuntimeException("Failed to make directory: " + file.getPath());
            }
        }

        if (!file.exists()) {
            try{
                InputStream input = Main.getInstance().getResource(defaultFilename);
                if (input == null) {
                    throw new RuntimeException("Could not create input stream for "+defaultFilename);
                }
                java.nio.file.Files.copy(input, file.toPath());
                input.close();
            } catch(IOException e) {
                e.printStackTrace();
            }
        }

        FileInputStream fileInputStream;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("Could not create input stream for "+file.getPath());
        }
        InputStreamReader reader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
        this.config = new YamlConfiguration();
        try {
            this.config.load(reader);
        } catch(InvalidConfigurationException e) {
            throw new RuntimeException("Invalid configuration in config file: "+file.getPath());
        } catch(IOException e) {
            throw new RuntimeException("Could not access file: "+file.getPath());
        }

        InputStream input = this.getClass().getClassLoader().getResourceAsStream(defaultFilename);
        if (input == null) {
            throw new RuntimeException("Could not create input stream for "+defaultFilename);
        }
        InputStreamReader default_reader = new InputStreamReader(input, StandardCharsets.UTF_8);
        this.defaultConfig = new YamlConfiguration();
        try {
            this.defaultConfig.load(default_reader);
        } catch(InvalidConfigurationException e) {
            throw new RuntimeException("Invalid configuration in config file: "+file.getPath());
        } catch(IOException e) {
            throw new RuntimeException("Could not access file: "+file.getPath());
        }

        try{
            fileInputStream.close();
            default_reader.close();
        } catch (IOException e) {
            throw new RuntimeException("Unable to finalize loading of config files.");
        }
    }

    public boolean contains(String path) {
        return config.contains(path);
    }

    public double getDouble(String path) {
        if (!config.contains(path)) {
            return defaultConfig.getDouble(path);
        } else {
            return config.getDouble(path);
        }
    }

    public int getInt(String path) {
        if (!config.contains(path)) {
            return defaultConfig.getInt(path);
        } else {
            return config.getInt(path);
        }
    }

    public int getDefaultInt(String path) {
        return defaultConfig.getInt(path);
    }

    public float getFloat(String path) {
        if (!config.contains(path)) {
            return (float) defaultConfig.getDouble(path);
        } else {
            return (float) config.getDouble(path);
        }
    }

    public String getString(String path) {
        String value = config.getString(path);
        if (value == null) {
            return defaultConfig.getString(path);
        } else {
            return value;
        }
    }

    public String getString(String path, String oldPath) {
        String value = config.getString(path);
        if (value == null) {
            String oldValue = config.getString(oldPath);
            if (oldValue == null) {
                return defaultConfig.getString(path);
            } else {
                return oldValue;
            }
        } else {
            return value;
        }
    }

    public List<String> getStringList(String path) {
        List<String> value = config.getStringList(path);
        if (value == null) {
            return defaultConfig.getStringList(path);
        } else {
            return value;
        }
    }

    public void reset(String path) {
        config.set(path, defaultConfig.get(path));
    }

    public void resetFile(String newDefaultFilename) {
        this.defaultFilename = newDefaultFilename;

        InputStream input = Main.getInstance().getResource(defaultFilename);
        if (input == null) {
            throw new RuntimeException("Could not create input stream for "+defaultFilename);
        }
        InputStreamReader reader = new InputStreamReader(input);
        this.config = YamlConfiguration.loadConfiguration(reader);
        this.defaultConfig = YamlConfiguration.loadConfiguration(reader);

    }

    public boolean getBoolean(String path) {
        if (!config.contains(path)) {
            return defaultConfig.getBoolean(path);
        } else {
            return config.getBoolean(path);
        }
    }

    public ConfigurationSection getConfigurationSection(String path) {
        ConfigurationSection section = config.getConfigurationSection(path);
        if (section == null) {
            return defaultConfig.getConfigurationSection(path);
        } else {
            return section;
        }
    }

    public ConfigurationSection getDefaultConfigurationSection(String path) {
        return defaultConfig.getConfigurationSection(path);
    }

    public void set(String path, Object value) {
        config.set(path, value);
    }

    public void saveConfig() {
        try {
            InputStream is = Main.getInstance().getResource(defaultFilename);
            if (is == null) {
                throw new RuntimeException("Could not create input stream for "+defaultFilename);
            }
            StringBuilder textBuilder = new StringBuilder(new String("".getBytes(), StandardCharsets.UTF_8));
            Reader reader = new BufferedReader(new InputStreamReader(is, Charset.forName(StandardCharsets.UTF_8.name())));
            int c;
            while((c = reader.read()) != -1) {
                textBuilder.append((char) c);
            }
            String yamlString = new String(textBuilder.toString().getBytes(), StandardCharsets.UTF_8);
            Map<String, Object> temp = config.getValues(true);
            for(Map.Entry<String, Object> entry: temp.entrySet()) {
                if (entry.getValue() instanceof Integer || entry.getValue() instanceof Double || entry.getValue() instanceof String || entry.getValue() instanceof Boolean || entry.getValue() instanceof List) {
                    String[] parts = entry.getKey().split("\\.");
                    int index = 0;
                    int i = 0;
                    for(String part : parts) {
                        if (i == 0) {
                            index = yamlString.indexOf(part+":", index);
                        } else {
                            index = yamlString.indexOf(" " + part+":", index);
                            index++;
                        }
                        i++;
                        if (index == -1) break;
                    }
                    if (index < 10)  continue;
                    int start = yamlString.indexOf(' ', index);
                    int end = yamlString.indexOf('\n', index);
                    if (end == -1) end = yamlString.length();
                    StringBuilder replace = new StringBuilder(new String("".getBytes(), StandardCharsets.UTF_8));
                    if (entry.getValue() instanceof List) {
                        if (((List<?>) entry.getValue()).isEmpty()) {
                            replace.append("[]");
                        } else {
                            replace.append("[");
                            for (Object o : (List<?>) entry.getValue()) {
                                replace.append(o.toString()).append(", ");
                            }
                            replace = new StringBuilder(replace.substring(0, replace.length() - 2));
                            replace.append("]");
                        }
                    } else {
                        replace.append(entry.getValue());
                    }
                    if (entry.getValue() instanceof String) {
                        replace.append("\"");
                        replace.reverse();
                        replace.append("\"");
                        replace.reverse();
                    }
                    StringBuilder builder = new StringBuilder(yamlString);
                    builder.replace(start+1, end, replace.toString());
                    yamlString = builder.toString();
                }
            }
            Writer fileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
            fileWriter.write(yamlString);
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}