package com.example.dao;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class FileDaoImpl implements FileDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	private static final Logger log = LoggerFactory.getLogger(NutritionDaoImpl.class);

	@Override
	public void addFile(String path, int id) {
		final String INSERT_SQL = "INSERT INTO files (path, id) VALUES (?, ?)";
		jdbcTemplate.update(INSERT_SQL, path, id);
	}

	@Override
	public void deleteFile(int id) {
		final String DEL_SQL = "DELETE from files where id = ?";
		jdbcTemplate.update(DEL_SQL, id);
	}

	@Override
	public List<Path> listFiles(int id) {
		List<Path> paths = new ArrayList<Path>();
		String sql = "SELECT * from files WHERE id = ?";
		List<Path> rows = this.jdbcTemplate.query(sql, new FileMapper(), id);
		return paths;
	}

	public static class FileMapper implements RowMapper<Path> {
		@Override
		public Path mapRow(ResultSet rs, int id) throws SQLException {
			Path path = Paths.get(rs.getString("path"));
			return path;
		}
	}

	@Override
	public void delAll(List<Integer> ids) {
		// TODO Auto-generated method stub
		for (int id : ids) {
			deleteFile(id);
		}
	}

}
