package com.ecep.contract.service;

import java.time.LocalDate;

import com.ecep.contract.converter.CustomerFileTypeStringConverter;
import com.ecep.contract.converter.InventoryStringConverter;
import com.ecep.contract.vo.CustomerFileTypeLocalVo;
import javafx.util.StringConverter;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.ecep.contract.MessageHolder;
import com.ecep.contract.util.ParamUtils;
import com.ecep.contract.vm.InventoryViewModel;
import com.ecep.contract.vo.InventoryVo;

@CacheConfig(cacheNames = "inventory")
@Service
public class InventoryService extends QueryService<InventoryVo, InventoryViewModel> {
    private final StringConverter<InventoryVo> stringConverter = new InventoryStringConverter(this);

    @Override
    public InventoryVo createNewEntity() {
        InventoryVo inventory = new InventoryVo();
        inventory.setCreateTime(LocalDate.now());
        inventory.setCreatorId(com.ecep.contract.Desktop.instance.getActiveEmployeeId());
        inventory.setActive(false);
        return inventory;
    }

    @Cacheable(key = "#p0")
    @Override
    public InventoryVo findById(Integer id) {
        return super.findById(id);
    }

    public InventoryVo findByCode(String code) {
        Page<InventoryVo> page = findAll(ParamUtils.builder().equals("code", code).build(), Pageable.ofSize(1));
        if (page.isEmpty()) {
            return null;
        }
        return page.getContent().getFirst();
    }

    public InventoryVo findByName(String text) {
        Page<InventoryVo> page = findAll(ParamUtils.builder().equals("name", text).build(), Pageable.ofSize(1));
        if (page.isEmpty()) {
            return null;
        }
        return page.getContent().getFirst();
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id")
    })
    @Override
    public InventoryVo save(InventoryVo entity) {
        return super.save(entity);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id")
    })
    @Override
    public void delete(InventoryVo entity) {
        super.delete(entity);
    }

    @Override
    public StringConverter<InventoryVo> getStringConverter() {
        return stringConverter;
    }
}
