package member.dao;

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

import member.dto.MemberDTO;

public class MemberDAO {
	
	// 연결 정보
	private String driver="oracle.jdbc.OracleDriver";
	private String url = "jdbc:oracle:thin:@localhost:1521:xe";
	private String db_id = "DBTEST";
	private String db_pw = "1234";
	private Connection con = null;
	private PreparedStatement pstmt = null;
	private ResultSet res = null;
	
	public MemberDAO() {
		try {
			Class.forName(driver);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// 쓰기
	public int write(MemberDTO dto) {
		try {
			String sql = "insert into member values(?,?,?,?,?,?,?,?,sysdate)";
			String[] arr =  new String[8];
			//arr = {"dto.getName()","dto.getId()","dto.getPwd()","dto.getGender()","dto.getEmail()","dto.getDomain()","dto.getTel()","dto.getAddr()"};
			con = DriverManager.getConnection(url,db_id,db_pw);
			pstmt = con.prepareStatement(sql);
//			for(int i=1;i<9;i++) {
//				pstmt.setString(i, arr[i-1]);
//			}
			pstmt.setString(1, dto.getName());
			pstmt.setString(2, dto.getId());
			pstmt.setString(3, dto.getPwd());
			pstmt.setString(4, dto.getGender());
			pstmt.setString(5, dto.getEmail());
			pstmt.setString(6, dto.getDomain());
			pstmt.setString(7, dto.getTel());
			pstmt.setString(8, dto.getAddr());
			int res=pstmt.executeUpdate();
			return res;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(pstmt!=null) pstmt.close();
				if(con!=null) con.close();
				if(res!=null) res.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return -1;
	}
	// write() end
	
	// 아이디 확인
	public boolean isExistId(String id) {
		boolean check = false;
		try {
			String sql ="select * from member";
			con = DriverManager.getConnection(url,db_id,db_pw);
			pstmt = con.prepareStatement(sql);
			res = pstmt.executeQuery();
			while(res.next()) {
				if(res.getString("ID").equals(id)){
				    check = true;
				    return check;
				} 
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(con!=null) con.close();
				if(pstmt!=null) pstmt.close();
				if(res!=null) res.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return check;
	}
	// isExistId() end
	
	// 로그인 
	public String login(String id, String pw) {
		String check = null;
		try {
			String sql ="select * from member where id=? and pwd=?";
			con = DriverManager.getConnection(url,db_id,db_pw);
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			pstmt.setString(2, pw);
			res = pstmt.executeQuery();
			if(res.next()) {
				check = res.getString("NAME");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(con!=null) con.close();
				if(pstmt!=null) pstmt.close();
				if(res!=null) res.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return check;
	}
	// login() end
}