package org.ts.ddcs.Worker;

import com.alibaba.fastjson.JSONObject;
import org.ts.ddcs.Log.LogHelper;
import org.ts.ddcs.utils.GBConstants;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Date;
import java.util.Set;
import java.util.concurrent.Callable;

@SuppressWarnings("all")
public class DataCommandRetryProcess implements Callable<Integer> {


    DataCommandRetryProcess() {

    }

    @Override
    public Integer call() throws Exception {
        try {
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            if (redisTemplate.hasKey("rtu_online")) {
                Set<String> keys = opsHash.keys("rtu_online");
                for (String rtuCode : keys) {
                    if (opsHash.hasKey(rtuCode, GBConstants.REDIS_KEY_COMMAND_FILE)) {
                        String commandJson = opsHash.get(rtuCode, GBConstants.REDIS_KEY_COMMAND_FILE);
                        JSONObject command = JSONObject.parseObject(commandJson);
                        boolean isTry = command.getBoolean("try");
                        boolean isNeedTry = command.getBoolean("needTry");
                        long tryCount = command.getLong("tryCount");
                        if (isTry && isNeedTry ) {
                            if (tryCount>=10){
                                opsHash.delete(rtuCode, GBConstants.REDIS_KEY_COMMAND_FILE);
                                if (redisTemplate.delete(rtuCode + ":" + GBConstants.REDIS_KEY_COMMAND_FILE)) {
                                    LogHelper.info(rtuCode + ": command clear : file down fail !!  clear  !");
                                }
                            }else {
                                if (command.containsKey("lastSendTime")) {
                                    long lastSendTime = command.getLong("lastSendTime");
                                    Date now = new Date();
                                    long currTime = now.getTime();
                                    long diff = currTime - lastSendTime;
                                    diff = diff / 1000;
                                    if (diff > 10) {
                                        LogHelper.info(rtuCode + " retry********************************** " + currTime + "    " + lastSendTime);
                                        DataProcess.DownloadNotify(rtuCode);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return 0;
    }
}
