package com.gyee.wisdom.dao.taoscz;

import com.gyee.wisdom.common.data.timeseries.BooleanTsData;
import com.gyee.wisdom.common.data.timeseries.DoubleTsData;
import com.gyee.wisdom.common.data.timeseries.TsData;
import com.gyee.wisdom.common.data.timeseries.TsDataType;
import com.gyee.wisdom.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;

@Slf4j
public class TaskCallable implements Callable<Map<String, TsData>> {

    private TaosConfig taosConfig;
    private long time;
    private String tagName;
    private TsDataType type;

    private long day_time = 86400000L;
    private long year_time = 8640000000L;

    public TaskCallable(TaosConfig taosConfig, long time, String tagName, TsDataType type) {
        this.taosConfig = taosConfig;
        this.time = time;
        this.tagName = tagName;
        this.type = type;
    }


    @Override
    public Map<String, TsData> call() {
        TsData tsData = null;
        Statement st = null;
        ResultSet rs = null;
        Map<String, TsData> result = new HashMap<>();

        if (StringUtil.isBlank(tagName))
            return result;

        try {
            st = taosConfig.getInstance().createStatement();
//            String point = TaosCovertUtil.coverStationPrefix(this.tagName) + "." + this.tagName.replace(".", "_");
//            String tableName = dbName+ "." + this.tagName;
            StringBuilder sb = new StringBuilder();
            sb.append("select last_row(*) from ").append(taosConfig.getDbName()).append(".")
                    .append(tagName).append(" where ts<=").append(time);
            //log.info(sql);
            rs = st.executeQuery(sb.toString());
            if (rs.next()) {
                if (this.type == TsDataType.DOUBLE)
                    tsData = new DoubleTsData(this.time, (short) 0, rs.getDouble(2));
                else if (this.type == TsDataType.BOOLEAN)
                    tsData = new BooleanTsData(this.time, (short) 0, rs.getBoolean(2));
            }
            result.put(this.tagName, tsData);
        } catch (Exception e) {
        } finally {
//            try {
//                if(rs != null)
//                    rs.close();
//                if(st != null)
//                    st.close();
//            } catch (SQLException e) {
//                e.printStackTrace();
//            }
        }
        return result;
    }
}
