/*
 * Copyright (c) 2016 Lucko (Luck) <luck@lucko.me>
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 */

package me.lucko.luckperms.common.config;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import me.lucko.luckperms.common.config.keys.EnduringKey;

import java.util.Set;
import java.util.stream.Collectors;

@SuppressWarnings("unchecked")
public abstract class AbstractConfiguration implements LPConfiguration {
    private final LoadingCache<ConfigKey<?>, Object> cache = CacheBuilder.newBuilder()
            .build(new CacheLoader<ConfigKey<?>, Object>() {
                @Override
                public Object load(ConfigKey<?> key) {
                    return key.get(AbstractConfiguration.this);
                }
            });

    @Override
    public <T> T get(ConfigKey<T> key) {
        return (T) cache.getUnchecked(key);
    }

    @Override
    public void loadAll() {
        ConfigKeys.getAllKeys().forEach(cache::getUnchecked);
    }

    @Override
    public void reload() {
        init();

        Set<ConfigKey<?>> toInvalidate = cache.asMap().keySet().stream().filter(k -> !(k instanceof EnduringKey)).collect(Collectors.toSet());
        cache.invalidateAll(toInvalidate);

        loadAll();
    }
}

@@ -1379,16 +1379,43 @@
 ngKey;%0A%0A
+import java.util.Optional;%0A
 import j
@@ -1614,23 +1614,33 @@
 Key%3C?%3E, 
+Optional%3C
 Object%3E
+%3E
  cache =
@@ -1715,23 +1715,33 @@
 Key%3C?%3E, 
+Optional%3C
 Object%3E
+%3E
 () %7B%0A   
@@ -1786,22 +1786,32 @@
  public 
+Optional%3C
 Object
+%3E
  load(Co
@@ -1855,16 +1855,36 @@
  return 
+Optional.ofNullable(
 key.get(
@@ -1910,16 +1910,17 @@
 on.this)
+)
 ;%0A      
@@ -2045,16 +2045,29 @@
 ked(key)
+.orElse(null)
 ;%0A    %7D%0A

Fix null config values throwing exception - closes #147