package com.tofly.latte_core.config;

import android.os.Handler;

import java.util.HashMap;

/**
 * 配置文件，处理一些初始化的工作
 */
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
public class Configurator {

    private static final HashMap<Object, Object> LATTE_CONFIGS = new HashMap<>();
    private static final Handler HANDLER = new Handler();

    private Configurator() {
        LATTE_CONFIGS.put(ConfigKeys.CONFIG_READY.name(), false);
        LATTE_CONFIGS.put(ConfigKeys.HANDLE.name(), HANDLER);
    }

    private static class Holder {
        private static final Configurator INSTANCE = new Configurator();
    }

    static Configurator getInstance() {
        return Holder.INSTANCE;
    }


    HashMap<Object, Object> getLatteConfigs() {
        return LATTE_CONFIGS;
    }

    public final void configure() {
        LATTE_CONFIGS.put(ConfigKeys.CONFIG_READY.name(), true);
    }

    public Configurator withApiHost(String apiHost) {
        LATTE_CONFIGS.put(ConfigKeys.API_HOST.name(), apiHost);
        return this;
    }

    public Configurator withInterceptor(boolean isNeedLog) {
        LATTE_CONFIGS.put(ConfigKeys.INTERCEPTOR.name(), isNeedLog);
        return this;
    }

    //检查是否配置成功
    private void checkConfigure() {
        final boolean isConfig = (boolean) LATTE_CONFIGS.get(ConfigKeys.CONFIG_READY.name());
        if (!isConfig) {
            throw new RuntimeException("Configuration is not ready,call configure");
        }
    }

    @SuppressWarnings("unchecked")
    final <T> T getConfiguration(Object key) {
        checkConfigure();
        final Object value = LATTE_CONFIGS.get(key);
        if (value == null) {
            throw new NullPointerException(key.toString() + " IS NULL");
        }
        return (T) LATTE_CONFIGS.get(key);
    }

}
