package com.gyee.edge.loader.sqlite.cache;


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.HashMap;
import java.util.Map;

@Slf4j
@Component
public class CacheService {

    @Autowired
    private Database db;


    private Map<String,DBPointMapper> map = new HashMap<>();

    public Map<String,DBPointMapper> getMap(){
        if (map.isEmpty()){
            map = loadDBPointMappers();
        }

        return map;
    }

    private Map<String,DBPointMapper> loadDBPointMappers(){
        Map<String,DBPointMapper> map = new HashMap<>();
        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_id(rs.getString("gyfp2_id"));
                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"));
                map.put(dbPointMapper.getPoint_key(),dbPointMapper);
            }
        } catch (Exception e) {
            log.info("sqlite查询失败",e);
            e.printStackTrace();
        }finally {
            db.releaseResource();
        }
        return map;
    }

}
