package com.bizzan.bitrade.service;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bizzan.bitrade.dao.GameWalletDao;
import com.bizzan.bitrade.entity.GameWallet;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class GameWalletService {

	@Autowired
	private GameWalletDao dao;
	@Autowired
	private MemberTransactionService transactionService;
	
	public GameWallet findOne(Long id) {
		GameWallet wallet = dao.findOne(id);
		if(wallet == null) {
			wallet = new GameWallet();
			wallet.setId(id);
			wallet.setBalance(BigDecimal.ZERO);
			wallet.setFrozenBalance(BigDecimal.ZERO);
			dao.save(wallet);
		}
		return wallet;
	}
	
	@Transactional(rollbackFor = Exception.class)
	public void transferIn(Long id, BigDecimal amount) {
		dao.increaseBalance(id, amount);
	}
	@Transactional(rollbackFor = Exception.class)
	public void transferOut(Long id, BigDecimal amount) {
		dao.decreaseBalance(id, amount);
	}
	
	@Transactional(rollbackFor = Exception.class)
	public boolean freeze(Long id, BigDecimal amount) {
		return dao.freezeBalance(id, amount)>0;
	}
	
	@Transactional(rollbackFor = Exception.class)
	public void clear(Long id, BigDecimal amount, BigDecimal fee, BigDecimal profit) {
		log.info("id={},amount={},fee={},profit={}", id, amount, fee, profit);
		dao.clear(id, amount.add(fee), amount.add(profit));
		String symbol = "USDT";
		transactionService.recordGameFee(id, symbol, fee);
		if(profit.compareTo(BigDecimal.ZERO)>0)
			transactionService.recordGameProfit(id, symbol, profit);
		else if(profit.compareTo(BigDecimal.ZERO)<0)
			transactionService.recordGameLoss(id, symbol, profit);
	}
}
