001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2022 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.util;
020
021import com.electronwill.nightconfig.core.Config;
022import com.electronwill.nightconfig.core.file.FileConfig;
023import java.io.File;
024import java.io.IOException;
025import java.util.ArrayList;
026import java.util.Collection;
027import java.util.HashMap;
028import java.util.List;
029import java.util.Map;
030import java.util.Optional;
031import java.util.StringTokenizer;
032import java.util.logging.Logger;
033import java.util.prefs.BackingStoreException;
034import org.jgrapes.core.Channel;
035import org.jgrapes.core.annotation.Handler;
036import org.jgrapes.core.events.Start;
037import org.jgrapes.util.events.ConfigurationUpdate;
038import org.jgrapes.util.events.FileChanged;
039import org.jgrapes.util.events.InitialConfiguration;
040
041/**
042 * A base class for configuration stored based on the 
043 * [night config library](https://github.com/TheElectronWill/night-config).
044 */
045@SuppressWarnings({ "PMD.GodClass" })
046public abstract class NightConfigStore extends ConfigurationStore {
047
048    protected static final Logger logger
049        = Logger.getLogger(NightConfigStore.class.getName());
050
051    protected FileConfig config;
052    protected Channel[] initialChannels;
053
054    /**
055     * Creates a new component with its channel set to the given 
056     * channel and the given file. The component handles
057     * {@link ConfigurationUpdate} events and {@link FileChanged}
058     * events for the configuration file (see
059     * @link #NightConfigStore(Channel, File, boolean, boolean)}
060     * 
061     * @param componentChannel the channel 
062     * @param file the file used to store the configuration
063     * @throws IOException
064     */
065    @Deprecated
066    public NightConfigStore(Channel componentChannel, File file)
067            throws IOException {
068        this(componentChannel, file, true, true);
069    }
070
071    /**
072     * Creates a new component with its channel set to the given 
073     * channel and the given file. The component handles
074     * {@link FileChanged} events for the configuration file (see
075     * @link #NightConfigStore(Channel, File, boolean, boolean)}
076     * 
077     * If `update` is `true`, the configuration file is updated
078     * when {@link ConfigurationUpdate} events are received.  
079     *
080     * @param componentChannel the channel
081     * @param file the file used to store the configuration
082     * @param update if the configuration file is to be updated
083     * @throws IOException Signals that an I/O exception has occurred.
084     */
085    @Deprecated
086    public NightConfigStore(Channel componentChannel, File file,
087            boolean update) throws IOException {
088        this(componentChannel, file, update, true);
089    }
090
091    /**
092     * Creates a new component with its channel set to the given 
093     * channel and the given file.
094     * 
095     * If `update` is `true`, the configuration file is updated
096     * when {@link ConfigurationUpdate} events are received.  
097     * 
098     * If `watch` is `true`, {@link FileChanged} events are processed
099     * and the configuration file is reloaded when it changes. Note
100     * that the generation of the {@link FileChanged} events must
101     * be configured independently (see {@link FileSystemWatcher}).
102     *
103     * @param componentChannel the channel
104     * @param file the file used to store the configuration
105     * @param update if the configuration file is to be updated
106     * @param watch if {@link FileChanged} events are to be processed
107     * @throws IOException Signals that an I/O exception has occurred.
108     */
109    @SuppressWarnings("PMD.ConstructorCallsOverridableMethod")
110    public NightConfigStore(Channel componentChannel, File file,
111            boolean update, boolean watch) throws IOException {
112        super(componentChannel);
113        if (update) {
114            Handler.Evaluator.add(this, "onConfigurationUpdate",
115                channel().defaultCriterion());
116        }
117        if (watch) {
118            Handler.Evaluator.add(this, "onFileChanged",
119                channel().defaultCriterion());
120        }
121        if (!file.exists()) {
122            file.createNewFile();
123        }
124    }
125
126    /**
127     * If watching the configuration file is enabled, fire
128     * a {@link ConfigurationUpdate} event with the complete
129     * configuration when the file changes. The event is fired
130     * on the same channel(s) as the {@link InitialConfiguration}
131     * event.
132     *
133     * @param event the event
134     */
135    @Handler(dynamic = true)
136    public void onFileChanged(FileChanged event) {
137        if (config.getNioPath().equals(event.path())
138            && event.change() == FileChanged.Kind.MODIFIED
139            && initialChannels != null) {
140            config.load();
141            ConfigurationUpdate updEvt = new ConfigurationUpdate();
142            addPrefs(updEvt, "/", config);
143            fire(updEvt, initialChannels);
144        }
145    }
146
147    @Override
148    @SuppressWarnings({ "PMD.AvoidBranchingStatementAsLastInLoop",
149        "PMD.CloseResource" })
150    public Optional<Map<String, Object>> structured(String path) {
151        if (!path.startsWith("/")) {
152            throw new IllegalArgumentException("Path must start with \"/\".");
153        }
154
155        // Walk down to node.
156        var segs = new StringTokenizer(path, "/");
157        Config cur = config;
158        while (segs.hasMoreTokens()) {
159            var nextSeg = segs.nextToken();
160            Object next = Optional.ofNullable(cur.get("_" + nextSeg))
161                .orElse(cur.get("/" + nextSeg));
162            if (next instanceof Config) {
163                cur = (Config) next;
164                continue;
165            }
166            return Optional.empty();
167        }
168        return Optional.of(toValueMap(cur));
169    }
170
171    private Map<String, Object> toValueMap(Config config) {
172        @SuppressWarnings("PMD.UseConcurrentHashMap")
173        Map<String, Object> result = new HashMap<>();
174        for (var entry : config.entrySet()) {
175            if (isNode(entry.getKey())) {
176                continue;
177            }
178            if (entry.getValue() instanceof Config) {
179                result.put(entry.getKey(), toValueMap(entry.getValue()));
180                continue;
181            }
182            if (entry.getValue() instanceof List<?> values) {
183                result.put(entry.getKey(), convertList(values));
184                continue;
185            }
186            result.put(entry.getKey(), entry.getValue());
187        }
188        return result;
189    }
190
191    private List<Object> convertList(List<?> values) {
192        List<Object> copy = new ArrayList<>();
193        for (var element : values) {
194            if (element instanceof Config cfg) {
195                copy.add(toValueMap(cfg));
196                continue;
197            }
198            copy.add(element);
199        }
200        return copy;
201    }
202
203    /**
204     * Checks if the name is an entry for a node.
205     *
206     * @param name the name
207     * @return true, if is node
208     */
209    protected boolean isNode(String name) {
210        if (name == null || name.length() < 1) {
211            return false;
212        }
213        char first = name.charAt(0);
214        return first == '_' || first == '/';
215    }
216
217    /**
218     * Intercepts the {@link Start} event and fires a
219     * {@link ConfigurationUpdate} event.
220     *
221     * @param event the event
222     * @throws BackingStoreException the backing store exception
223     * @throws InterruptedException the interrupted exception
224     */
225    @Handler(priority = 999_999, channels = Channel.class)
226    public void onStart(Start event)
227            throws BackingStoreException, InterruptedException {
228        ConfigurationUpdate updEvt = new InitialConfiguration();
229        addPrefs(updEvt, "/", config);
230        initialChannels = event.channels();
231        newEventPipeline().fire(updEvt, initialChannels).get();
232    }
233
234    private void addPrefs(ConfigurationUpdate updEvt, String path,
235            Config config) {
236        @SuppressWarnings("PMD.UseConcurrentHashMap")
237        Map<String, Object> atPath = new HashMap<>();
238        for (var e : config.entrySet()) {
239            if (isNode(e.getKey()) && e.getValue() instanceof Config) {
240                addPrefs(updEvt, ("/".equals(path) ? "" : path)
241                    + "/" + e.getKey().substring(1), e.getValue());
242                continue;
243            }
244            if (e.getValue() instanceof Config) {
245                atPath.put(e.getKey(), toValueMap(e.getValue()));
246            } else if (e.getValue() instanceof List<?> values) {
247                atPath.put(e.getKey(), convertList(values));
248            } else {
249                atPath.put(e.getKey(), e.getValue());
250            }
251        }
252        if (!atPath.isEmpty()) {
253            updEvt.set(path, atPath);
254        }
255    }
256
257    /**
258     * Merges and saves configuration updates.
259     *
260     * @param event the event
261     * @throws IOException Signals that an I/O exception has occurred.
262     */
263    @Handler(dynamic = true)
264    @SuppressWarnings({ "PMD.AvoidInstantiatingObjectsInLoops" })
265    public void onConfigurationUpdate(ConfigurationUpdate event)
266            throws IOException {
267        if (event instanceof InitialConfiguration) {
268            return;
269        }
270
271        boolean changed = false;
272        for (String path : event.paths()) {
273            if ("/".equals(path) && event.values(path).isEmpty()) {
274                // Special case, "remove root", i.e. all configuration data
275                config.clear();
276                changed = true;
277                continue;
278            }
279            if (handleSegment(config, new StringTokenizer(path, "/"),
280                event.structured(path).map(ConfigurationStore::flatten))) {
281                changed = true;
282            }
283        }
284        if (changed) {
285            config.save();
286        }
287    }
288
289    private boolean handleSegment(Config config,
290            StringTokenizer tokenizer, Optional<Map<String, Object>> values) {
291        if (!tokenizer.hasMoreTokens()) {
292            // "Leaf" map
293            return mergeValues(config, values.get());
294        }
295        boolean changed = false;
296        var nextSeg = tokenizer.nextToken();
297        var usSel = List.of("_" + nextSeg);
298        var slashSel = List.of("/" + nextSeg);
299        if (!tokenizer.hasMoreTokens() && values.isEmpty()) {
300            // Selected is last segment from path and we must remove
301            for (var sel : List.of(usSel, slashSel)) {
302                if (config.get(sel) != null) {
303                    // Delete sub-map.
304                    config.remove(sel);
305                    changed = true;
306                }
307            }
308            return changed;
309        }
310        // Check if sub config exists
311        Object subConfig = Optional.ofNullable(config.get(usSel))
312            .orElse(config.get(slashSel));
313        if (!(subConfig instanceof Config)) {
314            // Doesn't exist or is of wrong type, new sub-map
315            changed = true;
316            subConfig = config.createSubConfig();
317            config.set(usSel, subConfig);
318        }
319        // Continue with sub-map
320        return handleSegment((Config) subConfig, tokenizer, values) || changed;
321    }
322
323    @SuppressWarnings({ "PMD.CognitiveComplexity" })
324    private boolean mergeValues(Config config, Map<String, Object> values) {
325        boolean changed = false;
326        Map<String, Object> curValues = flatten(toValueMap(config));
327        for (var e : values.entrySet()) {
328            if (e.getValue() == null) {
329                // Delete from map (and config)
330                if (curValues.containsKey(e.getKey())) {
331                    curValues.remove(e.getKey());
332                    changed = true;
333                }
334                continue;
335            }
336            Object oldValue = curValues.get(e.getKey());
337            if (oldValue == null || !e.getValue().equals(oldValue)) {
338                curValues.put(e.getKey(), e.getValue());
339                changed = true;
340            }
341        }
342        if (changed) {
343            for (var itr = config.entrySet().iterator(); itr.hasNext();) {
344                if (!isNode(itr.next().getKey())) {
345                    itr.remove();
346                }
347            }
348            addToConfig(config, structure(curValues));
349        }
350        return changed;
351    }
352
353    @SuppressWarnings("unchecked")
354    private void addToConfig(Config config, Map<String, Object> map) {
355        for (var e : map.entrySet()) {
356            var selector = List.of(e.getKey());
357            if (e.getValue() instanceof Map) {
358                Config subConfig = config.get(selector);
359                if (subConfig == null) {
360                    subConfig = config.createSubConfig();
361                    config.set(selector, subConfig);
362                }
363                addToConfig(subConfig, (Map<String, Object>) e.getValue());
364            } else if (e.getValue() instanceof Collection) {
365                config.set(selector,
366                    checkCollection((Collection<?>) e.getValue()));
367            } else {
368                config.set(selector, e.getValue());
369            }
370        }
371    }
372
373    @SuppressWarnings("unchecked")
374    private Collection<Object> checkCollection(Collection<?> items) {
375        var checked = new ArrayList<>();
376        for (var item : items) {
377            if (item instanceof Map) {
378                Config subConfig = config.createSubConfig();
379                addToConfig(subConfig, (Map<String, Object>) item);
380                checked.add(subConfig);
381            } else if (item instanceof Collection) {
382                checked.add(checkCollection((Collection<?>) item));
383            } else {
384                checked.add(item);
385            }
386        }
387        return checked;
388    }
389
390}