package com.uas.platform.b2b.service.impl;


import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.uas.platform.b2b.dao.UsageLogDao;
import com.uas.platform.b2b.model.SearchFilter;
import com.uas.platform.b2b.model.UsageLog;
import com.uas.platform.b2b.service.UsageLogService;
import com.uas.platform.core.model.PageInfo;
import com.uas.platform.core.persistence.criteria.PredicateUtils;

@Service
public class UsageLogServiceImpl implements UsageLogService {

	@Autowired
	private UsageLogDao usageLogDao;

	@Override
	public void save(UsageLog logable) {
		usageLogDao.save(logable);
	}

	@Override
	public void save(Iterable<UsageLog> logables) {
		usageLogDao.save(logables);
	}

	@Override
	public Page<UsageLog> findAllByPageInfo(final PageInfo pageInfo, SearchFilter filter) {
		if (filter != null) {
			if(filter.getFromDate() != null) {
                pageInfo.expression(PredicateUtils.gte("time", new Long(filter.getFromDate()), false));
            }
			if(filter.getEndDate() != null) {
                pageInfo.expression(PredicateUtils.lte("time", new Long(filter.getEndDate()), false));
            }
		}
		Page<UsageLog> pageLogs = usageLogDao.findAll(new Specification<UsageLog>() {
			@Override
            public Predicate toPredicate(Root<UsageLog> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
				query.where(pageInfo.getPredicates(root, query, builder));
				return null;
			}
		}, pageInfo);
		return pageLogs;
	}

}
