package com.xhpc.pp.utils.security;

import cn.hutool.core.date.DateUtil;
import com.xhpc.pp.utils.HexUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.TimeUnit;

import static cn.hutool.core.date.DatePattern.NORM_DATETIME_FORMAT;
import static com.xhpc.common.core.utils.StringUtils.capitalize;
import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.pp.utils.security.CP56Time2a.cp56toDate;

public class CacheDataUtils {

    public static Object reflectTranslate(Object srcobj, Class tarclz, Class srcclz, Field[] targetfields) throws IllegalAccessException, InvocationTargetException, InstantiationException {

        Object tarobj = tarclz.getConstructors()[0].newInstance();
        for (Field tarfield : targetfields) {
            String tarFieldName = tarfield.getName();
            String srcval = null;
            try {
                srcval = (String) srcclz.getMethod("get".concat(capitalize(tarFieldName))).invoke(srcobj);
                Object tarval;
                if (tarfield.getType().getSimpleName().equals("Integer") && !tarfield.getName().equals("stopReason")) {
                    if (srcval.length() == 2) {
                        tarval = Integer.valueOf(srcval, 16);
                        if (tarfield.getName().endsWith("Temperature")) {
                            tarval = (Integer) tarval - 50;
                            tarval = (Integer) tarval > 0 ? tarval : 0;
                        }
                    } else {
                        tarval = HexUtils.reverseHexInt(srcval);
                    }
                } else if (tarFieldName.contains("ime")) {
                    tarval = DateUtil.format(cp56toDate(srcval), NORM_DATETIME_FORMAT);
                } else {
                    tarval = srcval;
                }
                tarclz.getMethod("set".concat(capitalize(tarFieldName)), tarfield.getType()).invoke(tarobj, tarval);
            } catch (NoSuchMethodException ignored) {
            }
        }
        return tarobj;
    }

    public static void hori2(String pileNo, String gunId) {

        String hori = "gun:".concat(pileNo).concat(gunId).concat(".hori");
        REDIS.setCacheObject(hori, "protection film", 300L, TimeUnit.MILLISECONDS);
    }

    public static boolean hori(String gunkey) {

        String hori = gunkey.concat(".hori");
        String HORI = REDIS.getCacheObject(hori);
        if (HORI != null) {
            return true;
        }
        REDIS.setCacheObject(hori, "protection film", 500L, TimeUnit.MILLISECONDS);
        return false;
    }

}
