package com.bizzan.bitrade.consumer;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.bizzan.bitrade.engine.ContractCoinMatchFactory;
import com.bizzan.bitrade.engine.TradingAccountMonitor;
import com.bizzan.bitrade.entity.CoinThumb;
import com.bizzan.bitrade.service.KLineService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class MarketListener implements MessageListener {
	@Autowired
	private RedisTemplate redisTemplate;
	
	@Autowired
	private ContractCoinMatchFactory matchFactory;
	@Autowired
    private TradingAccountMonitor tradingAccountMonitor;
	@Autowired
    private KLineService kLineService;
	
	private Map<String, BigDecimal> currentPriceMap = new ConcurrentHashMap<String, BigDecimal>();

	@Override
	public void onMessage(Message message, byte[] pattern) {
		// TODO Auto-generated method stub
		byte[] messageBody = message.getBody();
        Object msg = redisTemplate.getValueSerializer().deserialize(messageBody);
        //log.info("receive price, msg={}", msg);
        CoinThumb thumb = JSON.parseObject(msg.toString(), CoinThumb.class);
        thumb.setTime(System.currentTimeMillis()/1000);
        String symbol = thumb.getSymbol();
        if(!this.matchFactory.containsContractCoinMatch(symbol))
    		return;
        if(thumb.getClose().compareTo(BigDecimal.ZERO)<=0)
        	return;
        
        //this.kLineService.updateThumb(symbol, thumb);
        //this.matchFactory.getContractCoinMatch(symbol).refreshThumb(thumb);
        
        this.updatePrice(symbol, thumb.getClose());

        // 委托触发 or 爆仓
        this.matchFactory.getContractCoinMatch(symbol).refreshPrice(thumb);
	}
	
	public void updatePrice(String symbol, BigDecimal price) {
		currentPriceMap.put(symbol, price);
	}
	
	public Map<String, BigDecimal> getCurrentPriceMap() {
		return currentPriceMap;
	}

}
