package com.bizzan.bitrade.service;

import com.bizzan.bitrade.dao.ConfigRobotDao;
import com.bizzan.bitrade.entity.ConfigRobot;
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 ConfigRobotService extends BaseService {

    @Autowired
    private ConfigRobotDao configRobotDao;

    public ConfigRobot findOne(Long id) {
        return configRobotDao.findOne(id);
    }

    public ConfigRobot findBySymbol(String symbol) {
        return configRobotDao.findBySymbol(symbol);
    }

    public List<ConfigRobot> findAll() {
        return configRobotDao.findAll();
    }

    public Page<ConfigRobot> pageQuery(String symbol, Integer status, Pageable pageable) {
        Specification<ConfigRobot> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.hasText(symbol)) {
                predicates.add(cb.equal(root.get("symbol"), symbol));
            }
            if (status != null) {
                predicates.add(cb.equal(root.get("status"), status));
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        return configRobotDao.findAll(spec, pageable);
    }

    @Transactional(rollbackFor = Exception.class)
    public ConfigRobot create(ConfigRobot robot) {
        robot.setCreateTime(new Date());
        robot.setUpdateTime(new Date());
        return configRobotDao.save(robot);
    }

    @Transactional(rollbackFor = Exception.class)
    public ConfigRobot update(ConfigRobot robot) {
        robot.setUpdateTime(new Date());
        return configRobotDao.save(robot);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        configRobotDao.delete(id);
    }
}
