package com.gyee.edge.loader.sqlite;


import com.gyee.edge.loader.mapper.DBPointMapper;
import com.gyee.edge.loader.sqlite.config.Database;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class ReadDBPointData {
    @Autowired
    private Database db;

    public List<DBPointMapper> selectAllData() {
        List<DBPointMapper> dbPointMappers = new ArrayList<>();
        try {
            Connection conn = db.getConnection();
            String sql = "select * from dbpointmapper";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                DBPointMapper dbPointMapper = new DBPointMapper();
                dbPointMapper.setGyfp2_address(rs.getInt("gyfp2_address"));
                dbPointMapper.setGyfp2_valid(rs.getInt("gyfp2_valid"));
                dbPointMapper.setGyfp2_coeff(rs.getFloat("gyfp2_coeff"));
                dbPointMapper.setGyfp2_base(rs.getFloat("gyfp2_base"));
                dbPointMapper.setPoint_id(rs.getInt("point_id"));
                dbPointMapper.setPoint_type(rs.getInt("point_type"));
                dbPointMapper.setPoint_key(rs.getString("point_key"));
                dbPointMapper.setPoint_ratio(rs.getInt("point_ratio"));
                dbPointMappers.add(dbPointMapper);
            }
            db.releaseResource();
        } catch (Exception e) {
            log.info("sqlite查询失败",e);
            e.printStackTrace();
        }
        return dbPointMappers;
    }

    public DBPointMapper selectBykey(int gyfp2_address) {
        DBPointMapper dbPointMapper = new DBPointMapper();
        try {
            Connection conn = db.getConnection();
            String sql = "select * from dbpointmapper where gyfp2_address = ?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setInt(1,gyfp2_address);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                dbPointMapper.setGyfp2_address(rs.getInt("gyfp2_address"));
                dbPointMapper.setGyfp2_valid(rs.getInt("gyfp2_valid"));
                dbPointMapper.setGyfp2_coeff(rs.getFloat("gyfp2_coeff"));
                dbPointMapper.setGyfp2_base(rs.getFloat("gyfp2_base"));
                dbPointMapper.setPoint_id(rs.getInt("point_id"));
                dbPointMapper.setPoint_type(rs.getInt("point_type"));
                dbPointMapper.setPoint_key(rs.getString("point_key"));
                dbPointMapper.setPoint_ratio(rs.getInt("point_ratio"));
            }
            db.releaseResource();
        } catch (Exception e) {
            log.info("sqlite查询失败",e);
            e.printStackTrace();
        }
        return dbPointMapper;
    }
}
