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.ApplicationExt;
import id.iptek.utms.agent.model.PendingDownloadTask;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;

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

    public boolean updateIconUrl(ApplicationExt app) throws DatabaseException {
        boolean saved = false;
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = DBConn.getInstance().getConnection();
            conn.setAutoCommit(false);

            pstmt = conn.prepareStatement(""
                    + "update tms_application set icon_url=?,icon_url_exp=? where id=?::uuid");
            int idx = 1;
            pstmt.setString(idx++, app.getIconUrl());
            pstmt.setTimestamp(idx++, new Timestamp(app.getIconUrlExp().getTime()));
            pstmt.setString(idx++, app.getId());
            saved = pstmt.executeUpdate() == 1;
            
            conn.commit();
            conn.setAutoCommit(true);
        } catch (SQLException ex) {
            DBUtil.rollback(conn);
            throw new DatabaseException(ex);
        } finally {
            DBUtil.close(pstmt);
            DBUtil.close(conn);
        }
        return saved;
    }
    
    public boolean updateAppUrl(PendingDownloadTask task, ApplicationExt app) throws DatabaseException {
        boolean saved = false;
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = DBConn.getInstance().getConnection();
            conn.setAutoCommit(false);

            pstmt = conn.prepareStatement(""
                    + "update tms_download_task_application_link set download_url=?,download_url_exp=? where download_task_id=?::uuid and application_id=?::uuid");
            int idx = 1;
            pstmt.setString(idx++, app.getDownloadUrl());
            pstmt.setTimestamp(idx++, new Timestamp(app.getDownloadUrlExp().getTime()));
            pstmt.setString(idx++, task.getId());
            pstmt.setString(idx++, app.getId());
            saved = pstmt.executeUpdate() == 1;
            
            conn.commit();
            conn.setAutoCommit(true);
        } catch (SQLException ex) {
            DBUtil.rollback(conn);
            throw new DatabaseException(ex);
        } finally {
            DBUtil.close(pstmt);
            DBUtil.close(conn);
        }
        return saved;
    }

}
