package id.iptek.utms.agent.dao;

import id.iptek.utms.agent.db.DBConn;
import id.iptek.utms.agent.db.DBUtil;
import id.iptek.utms.agent.db.DatabaseException;
import id.iptek.utms.agent.model.TerminalIdObj;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Jaka
 */
public class TerminalDao {

    public TerminalDao() {
    }
    
    public List<TerminalIdObj> getTerminalIds() throws DatabaseException {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<TerminalIdObj> list = new ArrayList<>();
        try {
            conn = DBConn.getInstance().getConnection();
            pstmt = conn.prepareStatement(""
                    + "select id, sn  "
                    + "from tms_terminal "
                    + "where delete_ts is null");
            rs = pstmt.executeQuery();
            while (rs.next()) {
                String terminalId = rs.getString(1);
                String sn = rs.getString(2);
                list.add(new TerminalIdObj(sn, terminalId));
            }
        } catch(SQLException ex) {
            throw new DatabaseException(ex);
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        return list;
    }
    
    public TerminalIdObj getTerminalIdBySN(String sn) throws DatabaseException {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        TerminalIdObj terminalIdObj = null;
        try {
            conn = DBConn.getInstance().getConnection();
            pstmt = conn.prepareStatement(""
                    + "select id, sn  "
                    + "from tms_terminal "
                    + "where lower(sn)=? and delete_ts is null");
            pstmt.setString(1, sn.toLowerCase());
            rs = pstmt.executeQuery();
            if (rs.next()) {
                String terminalId = rs.getString(1);
                String _sn = rs.getString(2);
                terminalIdObj = new TerminalIdObj(_sn, terminalId);
            }
        } catch(SQLException ex) {
            throw new DatabaseException(ex);
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        return terminalIdObj;
    }

}
