package com.ffii.core.common.id.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ffii.core.common.id.dao.IdCounterDao;
import com.ffii.core.common.id.entity.IdCounter;
import com.ffii.core.support.AbstractIdEntityService;
import com.ffii.core.support.JdbcDao;

/** @author Fung */
@Service
public class IdCounterService extends AbstractIdEntityService<IdCounter, Integer, IdCounterDao> {

  public IdCounterService(JdbcDao jdbcDao, IdCounterDao dao) {
    super(jdbcDao, dao);
  }

  @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.SERIALIZABLE)
  public String getNextIdCount(String name, int length) {
    IdCounter instance = dao.findByName(name).orElseGet(() -> new IdCounter(name));
    instance.addOneCount();
    save(instance);
    return String.format("%0" + length + "d", instance.getCount());
  }
}
