package com.gyee.wisdom.dao.taoscz;

import com.gyee.wisdom.common.data.timeseries.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

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

@Slf4j
public class TaskCallable implements Callable {

    private Connection connection;
    private String sql;
    private long time;
    private String tagName;
    private TsDataType type;

    public TaskCallable(Connection connection, String sql, long time, String tagName, TsDataType type) {
        this.connection = connection;
        this.sql = sql;
        this.time = time;
        this.tagName = tagName;
        this.type = type;
    }


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

        if (!StringUtils.hasText(tagName))
            return result;

        try {
            st = this.connection.createStatement();
            rs = st.executeQuery(this.sql);

            if (rs.next()) {
                if (this.time <= 0)
                    this.time = rs.getLong(1);

                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));
                else if (this.type == TsDataType.STRING)
                    tsData = new StringTsData(this.time, (short) 0, rs.getString(2));
                else if (this.type == TsDataType.LONG)
                    tsData = new LongTsData(this.time, (short) 0, rs.getLong(2));
            } else {
                if (this.type == TsDataType.DOUBLE)
                    tsData = new DoubleTsData(this.time, (short) 0, 0);
                else if (this.type == TsDataType.BOOLEAN)
                    tsData = new BooleanTsData(this.time, (short) 0, false);
                else if (this.type == TsDataType.STRING)
                    tsData = new StringTsData(this.time, (short) 0, "0");
                else if (this.type == TsDataType.LONG)
                    tsData = new LongTsData(this.time, (short) 0, 0);
            }

            result.put(this.tagName, tsData);

        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            if (rs != null)
                rs.close();
            if (st != null)
                st.close();
            if (this.connection != null)
                this.connection.close();
        }

        return result;
    }

}
