package Juno2;


import java.io.*;
import java.util.HashMap;
import java.util.*;



public class CmdSellPositionImpl {


	public PositionListCVO doSellPosition(String userId, String userPassword, String acctId, String symbol)
	{
		PositionListCVO plcvo = new PositionListCVO();
		
		CmdDAOFactory daoFactory = CmdDAOFactory.getInstance();
        CmdDAO cdao = daoFactory.getDAO();
        try{
        	
			plcvo.setLoginVO(cdao.getLogin(userId, userPassword));
			
        } catch (Exception e) {
        	System.out.println("PositionListCVO setLoginVO(" + userId + ", " + userPassword + ") threw exception: " + e.getMessage());
        }
		
		if(plcvo.getLoginState()) {
			if(!userId.equals(plcvo.getUserId()))
                System.out.println("Session (" + userId +
                	") and request (" + plcvo.getUserId() +
                    ") user out of sync!");


			//// do same test for password
            //// on error invalidate session throw CmsException
            //// and redirect to login
        }


		//// no real validation


		CmdMarketDAO mktdao = new CmdMarketDAO();
        EquityVO evo = mktdao.getEquityPrice(symbol);
        
        System.out.println("");
        System.out.println("*** About to start sellPosition method ***");
        
   		try {
        	if(!cdao.sellPosition(userId, acctId, evo))
                throw new Exception();
    	} catch (Exception e){
           System.out.println("Fatal error sellPosition()" + userId + " , " + acctId + ", " + symbol);
           System.out.println("sellPosition(): " + e.getMessage());
    	}


		///// Sell complete - now build pos list
			
		try {
			plcvo.addPositionList(cdao.getPositionList(plcvo.getUserId(), acctId));
		} catch (Exception e) {
        	System.out.println("CmdSellPositionImpl addPositionList(" + plcvo.getUserId() + ", " + acctId + ") threw exception: " + e.getMessage());
		}
         //// now iterate cdao and grab symbols for pricing
        ArrayList symbolList = new ArrayList();
        HashMap pl = plcvo.getPositionList();
		Iterator poskeys = pl.keySet().iterator();
		while (poskeys.hasNext()) {
			String listSymbol = (String) poskeys.next();
			symbolList.add(listSymbol);
		}
		
		plcvo.addEquityList(mktdao.getEquityPrice(symbolList));


		return(plcvo);
 	}
}






