package com.eversec.service;

import com.arangodb.Predicate;
import com.google.gson.Gson;
import org.redkale.net.http.RestMapping;
import org.redkale.service.Service;
import org.redkale.source.CacheSource;
import org.redkale.util.AnyValue;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.function.Supplier;
import java.util.logging.Logger;

/**
 * @author: liangxianyou at 2018/10/22 11:49.
 */
public class BaseService implements Service {

    @Resource(name = "SERVER_ROOT")
    protected File webroot;
    @Resource(name = "APP_HOME")
    protected File apphome;

    public static Gson gson = new Gson();
    public Logger logger = Logger.getLogger(this.getClass().getSimpleName());
    public static final boolean winos = System.getProperty("os.name").contains("Window");
    public static boolean isWinos = System.getProperty("os.name").contains("Window");

    public static Predicate isEmpty = (x) -> {
        if (x == null)
            return true;
        if (x instanceof List)
            return ((List) x).isEmpty();
        if (x instanceof String)
            return ((String) x).isEmpty();
        if (x instanceof Map)
            return ((Map) x).isEmpty();
        if (x instanceof Collection)
            return ((Collection) x).isEmpty();
        return false;
    };

    @Resource(name = "cacheSource")
    protected CacheSource cacheSource;

    @Resource(name = "APP_HOME")
    protected File APP_HOME;

    public static Properties prop = new Properties();

    @Override
    public void init(AnyValue config) {
        try {
            File file = new File(APP_HOME.toPath() + "/conf/config.txt");
            if (file.exists()) {
                prop.load(new FileInputStream(file));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RestMapping(ignore = true)
    public <T> T getT(String key, Class<T> clazz, Supplier<T> supplier) {
        Object obj = cacheSource.getAndRefresh(key, 1000 * 60 * 3, clazz);
        if (obj != null) {
            return (T) obj;
        }

        T t = supplier.get();
        if (t != null) {
            cacheSource.set(1000 * 60 * 3, key, clazz, t);
        }
        return t;
    }

    @RestMapping(ignore = true)
    public String getProperty(String k, String defaultValue){
        return prop.getProperty(k, defaultValue).replace("${APP_HOME}", APP_HOME.getPath());
    }
    @RestMapping(ignore = true)
    public String getProperty(String k){
        return prop.getProperty(k);
    }

}
