package storage;

import java.util.ArrayList;

import org.json.JSONArray;

public class TradeHistory {
	public ArrayList<Trade> trades = new ArrayList<Trade>();
	public int numberOfBuyTrades = 0;
	public int numberOfSellTrades = 0;
	public double volumeOfBuyTrades = 0.0;
	public double volumeOfSellTrades = 0.0;
	public int timeframesec = 0;
	public long sinceid = 0;
	
	public TradeHistory(JSONArray array, long sinceid){
		if(array.length() < 1) return;
		
		double price;
		double value;
		int timestamp;
		String buyorsell;
		String marketorlimit;
		
		for(int i = 0;i < array.length();i++){
			price = array.getJSONArray(i).getDouble(0);
			value = array.getJSONArray(i).getDouble(1);
			timestamp = array.getJSONArray(i).getInt(2);
			buyorsell = array.getJSONArray(i).getString(3);
			marketorlimit = array.getJSONArray(i).getString(4);
				
			trades.add(new Trade(price,value,timestamp,buyorsell,marketorlimit));
			
			if(buyorsell.equals("b")){
				this.numberOfBuyTrades++;
				this.volumeOfBuyTrades += price;
			}else if(buyorsell.equals("s")){
				this.numberOfSellTrades++;
				this.volumeOfSellTrades += price;
			}
		}		
		
		this.sinceid = sinceid;
		this.timeframesec = array.getJSONArray(array.length()-1).getInt(2) - array.getJSONArray(0).getInt(2);
	}
	
	public TradeHistory(){}
	
	public TradeHistory getNumberAndVolumeOfBuyTradesInPastSec(int timeframe){
		int currenttimestamp = (int) (System.currentTimeMillis() / 1000L);
		TradeHistory returnHistory = new TradeHistory();
		
		for(Trade trade : trades){
			if(trade.time > (currenttimestamp-timeframe)){
				returnHistory.trades.add(trade);
			}
		}
		
		returnHistory.calculateNumberAndVolume();
		
		return returnHistory;
	}
		
	public void calculateNumberAndVolume(){
		for(Trade trade : trades){		
			if(trade.buyorsell.equals("b")){
				this.numberOfBuyTrades++;
				this.volumeOfBuyTrades += trade.price;
			}else if(trade.buyorsell.equals("s")){
				this.numberOfSellTrades++;
				this.volumeOfSellTrades += trade.price;
			}
		}		
		
		timeframesec = trades.get(trades.size()-1).time - trades.get(0).time;
	}

	public void clearTrades(){
		if(trades != null) trades.clear();
	}
	
}
