package com.bizzan.bitrade.service;

import com.bizzan.bitrade.dao.CurrencyCoinDao;
import com.bizzan.bitrade.entity.CurrencyCoin;
import com.bizzan.bitrade.service.Base.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CurrencyCoinService extends BaseService {

    @Autowired
    private CurrencyCoinDao currencyCoinDao;

    public CurrencyCoin save(CurrencyCoin coin) {
        return currencyCoinDao.save(coin);
    }

    public CurrencyCoin findOne(Long id) {
        return currencyCoinDao.findOne(id);
    }

    public CurrencyCoin findByCurrency(String currency) {
        return currencyCoinDao.findByCurrency(currency);
    }

    @Override
    public List<CurrencyCoin> findAll() {
        return currencyCoinDao.findAllByOrderByCurrencyAsc();
    }

    public Page<CurrencyCoin> findByCondition(String currency, Pageable pageable) {
        Specification<CurrencyCoin> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.hasText(currency)) {
                predicates.add(cb.like(cb.upper(root.get("currency")), "%" + currency.toUpperCase() + "%"));
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        return currencyCoinDao.findAll(spec, pageable);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            currencyCoinDao.delete(id);
        }
    }

    public CurrencyCoin create(CurrencyCoin coin) {
        coin.setCtime(new Date());
        coin.setMtime(new Date());
        return currencyCoinDao.save(coin);
    }

    public CurrencyCoin update(CurrencyCoin coin) {
        coin.setMtime(new Date());
        return currencyCoinDao.save(coin);
    }
}
