package sgcib.nemo.nails.server;


import com.isomorphic.util.DataTools;
import com.isomorphic.datasource.DataSourceManager;
import com.isomorphic.datasource.DataSource;
import com.isomorphic.log.*;
import java.util.*;

public class TradeStore 
{

    static Logger log = new Logger("nails");

    // itemID->supplyItem storage map - prepopulated from sql below
    static Map tradesById = new HashMap();

    static 
    {
        try 
        {
            // NOTE: The sample supplyItem dataset contains about 4,000 records.
            // grab at most 300 so we don't use too much memory
            DataSource ds = DataSourceManager.get("trades");
            List trades = ds.fetch(new HashMap());
            int maxRows = trades.size();
            if (maxRows > 300) maxRows = 300;
            for (int i = 0; i < maxRows; i++) 
            {
                Map properties = (Map)trades.get(i);
                Trade item = new Trade();
                // DataTools.setProperties() this is a SmartClient utility method that applies a
                // map of properties on an object using the Bean reflection mechanism
                DataTools.setProperties(properties, item);
                storeItem(item);
            }
        } catch (Exception e) {
            log.error("Failed to initialize SupplyItemStore", e);
        }
    }


    // delete the bean with the given itemID
    public static Trade removeItem(String tradeTrackingId)  {
        return (Trade)tradesById.remove(tradeTrackingId);
    }

   
    // get the supply item bean, given its itemID, or null if it can't be found
    public static Trade getItemByID(String tradeTrackingId)  {
        return (Trade) tradesById.get(tradeTrackingId);
    }

    public static List findMatchingItems(String trackingId) 
    {
        Collection items = tradesById.values();
        List matchingItems = new ArrayList();
        for (Iterator i = items.iterator(); i.hasNext(); ) 
        {
            Trade item = (Trade)i.next();
            if (trackingId != null && !trackingId.equals(item.getENTITY_TRACKING_ID())) continue;

            matchingItems.add(item);
        }
        return matchingItems;
    }
    public static Trade storeItem(Trade item) 
    {
        String itemID = item.getENTITY_TRACKING_ID();
       
        tradesById.put(itemID, item);
        return item;
    }
}

