package com.gyee.wisdom.alarm.sharding.taos;

import com.gyee.wisdom.alarm.sharding.model.TsPointData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;

@Slf4j
@Component
public class ReadValue {

    @Autowired
    TaosConfig taosConfig;

    public List<TsData> getValue1(String id, long startTs, long endTs) throws Exception {
        List<TsData> tsDataList = new ArrayList<>();
        Statement st = taosConfig.getInstance().createStatement();
        StringBuilder sb = new StringBuilder();
        sb.append("select * from ");
        sb.append(taosConfig.getTableName(id));
        sb.append(" where ts>='").append(DateFormatUtils.format(startTs, "yyyy-MM-dd HH:mm:ss:SSS"));
        sb.append("' and ts<='").append(DateFormatUtils.format(endTs, "yyyy-MM-dd HH:mm:ss:SSS"));
        sb.append("'");
        ResultSet rs = st.executeQuery(sb.toString());
        while (rs.next()) {
            tsDataList.add(new StringTsData(rs.getLong(1), (short) 0, rs.getString(2)));
        }

        return tsDataList;
    }

    public List<TsData>  getValue2(String id, long startTs, long endTs,int interval) throws Exception {
        List<TsData> tsDataList = new ArrayList<>();
        Statement st = taosConfig.getInstance().createStatement();
        StringBuilder sb = new StringBuilder();
        sb.append("select last(value) from ");
        sb.append(taosConfig.getTableName(id));
        sb.append(" where ts>='").append(DateFormatUtils.format(startTs, "yyyy-MM-dd HH:mm:ss:SSS"));
        sb.append("' and ts<='").append(DateFormatUtils.format(endTs, "yyyy-MM-dd HH:mm:ss:SSS"));
        sb.append("' interval(").append(interval).append("s) fill(prev)");
        ResultSet rs = st.executeQuery(sb.toString());
        while (rs.next()) {
            tsDataList.add(new StringTsData(rs.getLong(1), (short) 0, rs.getString(2)));
        }
        return tsDataList;
    }
}
