/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ejb;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.PostActivate;
import javax.ejb.PrePassivate;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.sql.DataSource;

/**
 *
 * @author Administrator
 */
@Stateful
public class StatefulAccount implements StatefulAccountRemote, StatefulAccountLocal {
    @Resource(name = "sample1")
    private DataSource sample;

   // @Resource(name = "mysample")
   // private DataSource mysample;
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    private Connection connection;
    private double account = -1.0;

    public StatefulAccount() {
    }

    @PostConstruct
    @PostActivate
    public void openConnection() {
        try {
            connection = sample.getConnection();
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        }
    }

    @PrePassivate
    @PreDestroy
    public void cleanup() {
        try {
            connection.close();
            connection = null;
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        }
    }

    public void depoist(double amount) throws Exception {
        if (amount < 0) {
            throw new Exception("Invalid amount");
        }
        account += amount;

    }

    public void withdraw(double amount) throws Exception {
        if (amount < 0) {
            throw new Exception("Invalid amount");
        }
        if (account < amount) {
            throw new Exception("not engouch money");
        }
        account -= amount;
    }

    public double getBalance(String id) {
        if (account < 0) {
            if (connection != null) {
                String sql = "Select amount from account where id= " + id;
                try {
                    Statement s = connection.createStatement();
                    ResultSet re = s.executeQuery(sql);
                    if (re.next()) {
                        account = re.getInt("amount");
                    }
                } catch (Exception e) {
                    System.out.println(e.toString());
                }
            }
        }
        return account;
    }

    @Remove
    public void updateAccount(String id) {
        if (connection != null) {
            String sql = "update account set amount =? where id= " + id;
            try {
                PreparedStatement s = connection.prepareStatement(sql);
                s.setDouble(1, account);
                int re = s.executeUpdate();
            } catch (Exception e) {
                System.out.println(e.toString());
            }
        }
    }
}
