package de.avatic.lcc.repositories;

import de.avatic.lcc.model.nodes.Distance;
import de.avatic.lcc.model.nodes.DistanceMatrixState;
import de.avatic.lcc.model.nodes.Node;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;

@Repository
public class DistanceMatrixRepository {
    private final JdbcTemplate jdbcTemplate;

    public DistanceMatrixRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public Optional<Distance> getDistance(Node src, Node dest) {

        String query = "SELECT * FROM distance_matrix WHERE from_node_id = ? AND to_node_id = ? AND state = ?";

        var distance = jdbcTemplate.query(query, new DistanceMapper(), src.getId(), dest.getId(), DistanceMatrixState.VALID);

        if(distance.isEmpty())
            return Optional.empty();

        return Optional.of(distance.getFirst());
    }

    private static class DistanceMapper implements RowMapper<Distance> {
        @Override
        public Distance mapRow(ResultSet rs, int rowNum) throws SQLException {
            Distance entity = new Distance();

            entity.setFromNodeId(rs.getInt("from_node_id"));
            entity.setToNodeId(rs.getInt("to_node_id"));
            entity.setDistance(rs.getBigDecimal("distance"));
            entity.setFromGeoLng(rs.getBigDecimal("from_geo_lng"));
            entity.setFromGeoLat(rs.getBigDecimal("from_geo_lat"));
            entity.setToGeoLng(rs.getBigDecimal("to_geo_lng"));
            entity.setToGeoLat(rs.getBigDecimal("to_geo_lat"));
            entity.setState(DistanceMatrixState.valueOf(rs.getString("state")));
            entity.setUpdatedAt(rs.getTimestamp("updated_at").toLocalDateTime());


            return entity;
        }
    }
}
