package cn.lihongjie.coal.dataCollectorLog.service;

import static org.springframework.data.domain.Sort.Order.asc;

import static java.util.Collections.singletonList;

import cn.lihongjie.coal.base.dto.CommonQuery;
import cn.lihongjie.coal.base.dto.IdRequest;
import cn.lihongjie.coal.base.service.BaseService;
import cn.lihongjie.coal.dataCollectorLog.dto.CreateDataCollectorLogDto;
import cn.lihongjie.coal.dataCollectorLog.dto.DataCollectorLogDto;
import cn.lihongjie.coal.dataCollectorLog.dto.UpdateDataCollectorLogDto;
import cn.lihongjie.coal.dataCollectorLog.entity.DataCollectorLogEntity;
import cn.lihongjie.coal.dataCollectorLog.mapper.DataCollectorLogMapper;
import cn.lihongjie.coal.dataCollectorLog.repository.DataCollectorLogRepository;
import cn.lihongjie.coal.dbFunctions.DbFunctionService;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@Transactional
public class DataCollectorLogService
        extends BaseService<DataCollectorLogEntity, DataCollectorLogRepository> {
    @Autowired private DataCollectorLogRepository repository;

    @Autowired private DataCollectorLogMapper mapper;

    @Autowired private ConversionService conversionService;

    @Autowired private DbFunctionService dbFunctionService;

    public DataCollectorLogDto create(CreateDataCollectorLogDto request) {
        DataCollectorLogEntity entity = mapper.toEntity(request);

        this.repository.save(entity);
        return getById(entity.getId());
    }

    public DataCollectorLogDto update(UpdateDataCollectorLogDto request) {
        DataCollectorLogEntity entity = this.repository.get(request.getId());
        this.mapper.updateEntity(entity, request);

        this.repository.save(entity);

        return getById(entity.getId());
    }

    public void delete(IdRequest request) {
        this.repository.deleteAllById(request.getIds());
    }

    public DataCollectorLogDto getById(String id) {
        DataCollectorLogEntity entity = repository.get(id);

        return mapper.toDto(entity);
    }

    public Page<DataCollectorLogDto> list(CommonQuery query) {
        Page<DataCollectorLogEntity> page =
                repository.findAll(
                        query.specification(conversionService),
                        PageRequest.of(
                                query.getPageNo(),
                                query.getPageSize(),
                                Sort.by(CollectionUtils.isEmpty(query.getOrders()) ? singletonList(asc("createTime"))  : query.getOrders())));

        return page.map(this.mapper::toDto);
    }
}
