package cn.lihongjie.coal.ipList.service;

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.common.Constants;
import cn.lihongjie.coal.ipList.dto.CreateIpListDto;
import cn.lihongjie.coal.ipList.dto.IpListDto;
import cn.lihongjie.coal.ipList.dto.UpdateIpListDto;
import cn.lihongjie.coal.ipList.entity.IpListEntity;
import cn.lihongjie.coal.ipList.mapper.IpListMapper;
import cn.lihongjie.coal.ipList.repository.IpListRepository;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
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 IpListService extends BaseService<IpListEntity, IpListRepository> {
    @Autowired private IpListRepository repository;

    @Autowired private IpListMapper mapper;

    @Autowired private ConversionService conversionService;

    @CacheEvict(value = Constants.CACHE_ADDRESS_TYPE, allEntries = true)
    public IpListDto create(CreateIpListDto request) {
        IpListEntity entity = mapper.toEntity(request);

        this.repository.save(entity);
        return getById(entity.getId());
    }
    @CacheEvict(value = Constants.CACHE_ADDRESS_TYPE, allEntries = true)

    public IpListDto update(UpdateIpListDto request) {
        IpListEntity entity = this.repository.get(request.getId());
        this.mapper.updateEntity(entity, request);

        this.repository.save(entity);

        return getById(entity.getId());
    }
    @CacheEvict(value = Constants.CACHE_ADDRESS_TYPE, allEntries = true)
    public void delete(IdRequest request) {
        this.repository.deleteAllById(request.getIds());
    }

    public IpListDto getById(String id) {
        IpListEntity entity = repository.get(id);

        return mapper.toDto(entity);
    }

    public Page<IpListDto> list(CommonQuery query) {
        Page<IpListEntity> page =
                repository.findAll(
                        query.specification(conversionService),
                        PageRequest.of(
                                query.getPageNo(),
                                query.getPageSize(),
                                Sort.by(query.getOrders())));

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

    @Cacheable(value = Constants.CACHE_ADDRESS_TYPE, key = "#address")
    public String getAddressType(String address) {
        return this.repository.getAddressType(address);

    }
}
