package com.axelor.apps.stock.service;

import com.axelor.apps.base.db.Company;
import com.axelor.apps.base.db.Product;
import com.axelor.apps.stock.db.InternalTrackingNumber;
import com.axelor.apps.stock.db.StockConfig;
import com.axelor.apps.stock.db.TrackingNumber;
import com.axelor.apps.stock.db.repo.InternalTrackingNumberRepository;
import com.axelor.apps.stock.db.repo.StockConfigRepository;
import com.axelor.exception.AxelorException;
import com.axelor.inject.Beans;
import com.google.inject.persist.Transactional;
import java.time.LocalDate;

public class InternalTrackingNumberService {

  @Transactional(rollbackOn = {Exception.class})
  public InternalTrackingNumber createInternalTrackingNumber(
      Product product, Company company, LocalDate date, TrackingNumber trackingNumber)
      throws AxelorException {

    InternalTrackingNumber internalTrackingNumber = new InternalTrackingNumber();
    internalTrackingNumber.setProduct(product);
    internalTrackingNumber.setTrackingNumber(trackingNumber);
    internalTrackingNumber.setPerishableExpirationDate(
        trackingNumber.getPerishableExpirationDate());
    internalTrackingNumber.setFabricationDate(internalTrackingNumber.getFabricationDate());
    internalTrackingNumber.setReceptionDate(date);

    Long categoryId = product.getFamilleProduit().getId();

    StockConfig stockConfig =
        Beans.get(StockConfigRepository.class).all().filter("self.company = ?", company).fetchOne();

    String sequence = "";

    switch (categoryId.intValue()) {
      case 67:
        sequence = Beans.get(StockMoveToolServiceImpl.class).getInternalSequence(36, company, date);
        stockConfig.setMpInternalSeq((stockConfig.getMpInternalSeq() + 1));
        break;
      case 68:
        sequence = Beans.get(StockMoveToolServiceImpl.class).getInternalSequence(36, company, date);
        stockConfig.setMpInternalSeq((stockConfig.getMpInternalSeq() + 1));
        break;
      case 59:
        sequence = Beans.get(StockMoveToolServiceImpl.class).getInternalSequence(35, company, date);
        stockConfig.setAcInternalSeq((stockConfig.getMpInternalSeq() + 1));
        break;
      default:
        // sequence = "AC" + stockConfig.getAcInternalSeq() + month + formattedYear;
        // stockConfig.setAcInternalSeq((stockConfig.getMpInternalSeq() + 1));
        break;
    }

    Beans.get(StockConfigRepository.class).save(stockConfig);
    internalTrackingNumber.setTrackingNumberSeq(sequence);

    return internalTrackingNumber;
  }

  public InternalTrackingNumber getInternalTrackingNumber(
      Product product, TrackingNumber trackingNumber) {
    InternalTrackingNumber internalTrackingNumber =
        Beans.get(InternalTrackingNumberRepository.class)
            .all()
            .filter("self.product = ?1 and self.trackingNumber = ?2", product, trackingNumber)
            .fetchOne();

    return internalTrackingNumber;
  }
}
