package com.gyee.wisdom.report.config.cache;


import com.gyee.wisdom.report.config.sqlite.Database;
import com.gyee.wisdom.report.entity.WindpowerStation;
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;


@Component
public class CacheService {

    @Autowired
    private Database db;

    private List<WindpowerStation> windpowerStations;


    public List<WindpowerStation> getWindpowerStations() {
        if (windpowerStations == null) {
            windpowerStations = loadWindPowerStations();
        }

        return windpowerStations;
    }

    public int getSerial(String wname,String areaid){

        List<WindpowerStation> windpowerStations = getWindpowerStations();
        for (WindpowerStation windpowerStation : windpowerStations){
            if (windpowerStation.getWname().equals(wname) && windpowerStation.getAreaid().equals(areaid)){
                return windpowerStation.getSerial();
            }
        }
        return 1;
    }


    private List<WindpowerStation> loadWindPowerStations() {
        // DONE: 从数据库中加载WindpowerStation
        List<WindpowerStation> windpowerStationList = new ArrayList<>();
        try {
            Connection conn = db.getConnection();
            String sql = "select * from windpowerstation";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                WindpowerStation windpowerStation = new WindpowerStation();
                windpowerStation.setId(rs.getInt("id"));
                windpowerStation.setWname(rs.getString("wname"));
                windpowerStation.setSerial(rs.getInt("serial"));
                windpowerStation.setArea(rs.getString("area"));
                windpowerStation.setAreaid(rs.getString("areaid"));
                windpowerStationList.add(windpowerStation);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            db.releaseResource();
        }
        return windpowerStationList;
    }
}
