package seller;

import java.rmi.RemoteException;
import javax.ejb.*;
import java.util.*;
import java.text.NumberFormat;
import java.io.Serializable;
import javax.naming.*;
import javax.jts.*;
import auction.*;
import registration.*;

public class SellerBean implements SessionBean, 
			SessionSynchronization {

    private transient SessionContext ctx;
    private transient Properties p = new Properties();
    private transient boolean success = true;

    public void afterBegin() {
    }

    public void beforeCompletion() {
	
	if (!success ) {
	   ctx.setRollbackOnly();
	}
    }

    public void afterCompletion(boolean state) {
    }

    public int insertItem(String seller, String password, 
			String description, int auctiondays, 
			double startprice, String summary) 
			throws RemoteException { 

        try{
        Context jndiCtx = new InitialContext(p);

	RegistrationHome rhome = (RegistrationHome) 
			jndiCtx.lookup("registration");
	RegistrationPK rpk=new RegistrationPK();
	rpk.theuser=seller;
	Registration newseller=rhome.findByPrimaryKey(rpk);

	if((newseller == null) || 
		(!newseller.verifyPassword(password))) {
            return(Auction.INVALID_USER);	
	}
	newseller.adjustAccount(-0.50);

        AuctionItemHome home = (AuctionItemHome) 
			jndiCtx.lookup("auctionitems");
        AuctionItem ai= home.create(seller, description, 
			auctiondays, startprice, summary);
	if(ai == null) {
	   success=false;
           return Auction.INVALID_ITEM;
	} 
	else {
           return(ai.getId()); 
	}

        }catch(Exception e){ 
           System.out.println("insert problem="+e);
	   success=false;
           return Auction.INVALID_ITEM;
        }
    }

    public void ejbCreate() throws CreateException, RemoteException {
        p.put(Context.INITIAL_CONTEXT_FACTORY, 
		"weblogic.jndi.TengahInitialContextFactory");
    }

    public void setSessionContext(SessionContext ctx) 
		throws RemoteException {
        this.ctx = ctx;
    }

    public void unsetSessionContext() throws RemoteException {   
        ctx = null;  
    } 

    public void ejbRemove() {}
    public void ejbActivate() throws RemoteException { }
    public void ejbPassivate() throws RemoteException { }
}


