package net.tccn.base;

import org.redkale.annotation.Resource;
import org.redkale.convert.json.JsonConvert;
import org.redkale.service.RetResult;
import org.redkale.service.Service;
import org.redkale.source.CacheMemorySource;
import org.redkale.source.DataSource;
import org.redkale.util.Sheet;

import java.io.File;
import java.util.List;
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 {

    protected final static JsonConvert convert = JsonConvert.root();

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

    protected Logger logger = Logger.getLogger(this.getClass().getSimpleName());

    protected static boolean isWinos = System.getProperty("os.name").contains("Window");

    @Resource(name = "cache")
    protected static CacheMemorySource cacheSource = new CacheMemorySource("cache");

    @Resource(name = "APP_HOME")
    protected File APP_HOME;
    @Resource(name = "meta")
    protected DataSource metaSource;
    @Resource
    protected MetaKit metaKit;


    protected static Properties prop = new Properties();
    protected static TplKit tplKit = TplKit.use(true);
    private static boolean tplInit = false;

    protected final static RetResult RET_SUCCESS = RetResult.success();
    protected final static RetResult RET_EMPTY_SHEET = RetResult.success(new Sheet<>(0, List.of()));
    protected final static RetResult RET_EMPTY_LIST = RetResult.success(List.of());

    protected RetResult retError(String info) {
        return new RetResult<>(100, info);
    }

    protected RetResult retError(int code, String info) {
        return new RetResult<>(code, info);
    }

    protected <T> RetResult<T> render(T obj) {
        return new RetResult<>(obj);
    }

    protected RetResult render() {
        return RET_SUCCESS;
    }


    protected <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;
    }

    protected Integer platId(String token) {
        return MetaKit.getPlatId(token);
    }

    protected boolean isEmpty(Object obj) {
        return Utils.isEmpty(obj);
    }
}
