package cart;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import bbs.Bbs;

public class Cart {

	private Connection conn;
	private ResultSet rs;
	
	private int P_NO;
	private int PNUM;
	
	public int getP_NO() {
		return P_NO;
	}

	public void setP_NO(int p_NO) {
		P_NO = p_NO;
	}

	public int getPNUM() {
		return PNUM;
	}

	public void setPNUM(int pNUM) {
		PNUM = pNUM;
	}

	public Cart() {
		try {
			String dbURL = "jdbc:oracle:thin:@localhost:1521:ORCL";
			String dbID = "-";
			String dbPassword = "-";
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection(dbURL, dbID, dbPassword);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public int getNext() {
		String SQL = "SELECT C_NO FROM CART ORDER BY C_NO DESC";
		try{

			PreparedStatement pstmt = conn.prepareStatement(SQL);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				return rs.getInt(1) + 1;
			}
			return 1; //현재가 첫 번째 게시글인 경우
		}catch (Exception e) {
			e.printStackTrace();
		}
		return -1; //db오류
	}
	
	public int write(int pno, int pnum) {
		String SQL = "INSERT INTO CART VALUES (?, ?, ?)";
		try{
			PreparedStatement pstmt = conn.prepareStatement(SQL);
			pstmt.setInt(1, getNext());
			pstmt.setInt(2, pno);
			pstmt.setInt(3, pnum);
			pstmt.executeUpdate();
			return pstmt.executeUpdate();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return -1; //db오류
	}
	
	public int delete(int pno, int pnum) {
		String SQL = "DELETE FROM CART WHERE P_NO = ? AND PNUM = ? ";
		try{
			PreparedStatement pstmt = conn.prepareStatement(SQL);
			pstmt.setInt(1, pno);
			pstmt.setInt(2, pnum);
			pstmt.executeUpdate();
			return pstmt.executeUpdate();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return -1; //db오류
	}
	
	public ArrayList<Bbs> getPro(int user_no){
		String SQL = "SELECT P_NO FROM CART WHERE PNUM = ?";
		ArrayList<Bbs> list = new ArrayList<Bbs>();
		try {
			 PreparedStatement pstmt = conn.prepareStatement(SQL);
			 pstmt.setInt(1, user_no);
			 rs = pstmt.executeQuery();
			 while (rs.next()) {
				 Bbs bbs = new Bbs();
				 bbs.setPro_num(rs.getInt(1));
				 list.add(bbs);
			 } 
		 } catch (Exception e) {
			 e.printStackTrace();
		 }
		 return list;
	}
}
