package com.axelor.apps.stock.db.repo;

import com.axelor.apps.base.service.administration.SequenceService;
import com.axelor.apps.stock.db.StockProductionRequest;
import com.axelor.inject.Beans;
import com.google.common.base.Strings;
import javax.persistence.PersistenceException;

public class StockProductionRequestManagementRepository extends StockProductionRequestRepository {

  @Override
  public StockProductionRequest save(StockProductionRequest entity) {
    try {
      StockProductionRequest productionRequest = super.save(entity);
      SequenceService sequenceService = Beans.get(SequenceService.class);

      if (Strings.isNullOrEmpty(productionRequest.getStockProductionRequestSeq())) {
        productionRequest.setStockProductionRequestSeq(
            sequenceService.getDraftSequenceNumber(productionRequest));
      }

      if (Strings.isNullOrEmpty(productionRequest.getName())
          || productionRequest
              .getName()
              .startsWith(productionRequest.getStockProductionRequestSeq())) {
        productionRequest.setName(productionRequest.getStockProductionRequestSeq());
      }

      return productionRequest;
    } catch (Exception e) {
      throw new PersistenceException(e);
    }
  }
}
