package com.management.dao.impl.calcs;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.management.bean.calculate.ProjectCalc;
import com.management.bean.calculate.ProjectCalcs;
import com.management.dao.calcs.ProjectCalcDao;
import com.management.util.DBUtil;

public class ProjectCalcDaoImpl implements ProjectCalcDao {

	@Override
	public List<ProjectCalc> find() {
		try {
			Connection conn = DBUtil.getConnection();
			String sql = "select * from project_calc";
			QueryRunner qr = new QueryRunner();
			return qr.query(conn, sql, new BeanListHandler<>(ProjectCalc.class));
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public void add(ProjectCalc c) {
		try {
			Connection conn = DBUtil.getConnection();
			String sql = "insert into project_calc(rank,category,weight,high,low) values(?,?,?,?,?)";
			QueryRunner qr = new QueryRunner();
			Object[] params = {c.getRank(),c.getCategory(),c.getWeight(),c.getHigh(),c.getLow()};
			qr.update(conn, sql, params);
			ProjectCalcs.update();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public void update(ProjectCalc c) {
		try {
			Connection conn = DBUtil.getConnection();
			String sql = "update project_calc set rank=?,category=?,weight=?,high=?,low=? where id=?";
			QueryRunner qr = new QueryRunner();
			Object[] params = {c.getRank(),c.getCategory(),c.getWeight(),c.getHigh(),c.getLow(),c.getId()};
			qr.update(conn, sql, params);
			ProjectCalcs.update();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public void delete(int id) {
		try {
			Connection conn = DBUtil.getConnection();
			String sql = "delete from project_calc where id=?";
			QueryRunner qr = new QueryRunner();
			qr.update(conn, sql,id);
			ProjectCalcs.update();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
}
