/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2019 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.axelor.apps.stock.service;

import com.axelor.apps.base.db.Product;
import com.axelor.apps.base.db.repo.ProductRepository;
import com.axelor.apps.stock.db.Inventory;
import com.axelor.apps.stock.db.InventoryLine;
import com.axelor.apps.stock.db.StockLocation;
import com.axelor.apps.stock.db.StockLocationLine;
import com.axelor.apps.stock.db.TrackingNumber;
import com.axelor.apps.stock.db.repo.InventoryLineRepository;
import com.axelor.apps.stock.db.repo.TrackingNumberRepository;
import com.axelor.auth.AuthUtils;
import com.axelor.db.Query;
import com.axelor.inject.Beans;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;

public class InventoryLineService {

  @Inject private ProductRepository productRepository;
  private TrackingNumberRepository trackingNumberRepository;
  private InventoryLineRepository inventoryLineRepository;

  public InventoryLine createInventoryLine(
      Inventory inventory,
      Product product,
      BigDecimal currentQty,
      String rack,
      TrackingNumber trackingNumber) {

    InventoryLine inventoryLine = new InventoryLine();
    inventoryLine.setInventory(inventory);
    inventoryLine.setProduct(product);
    inventoryLine.setRack(rack);
    inventoryLine.setCurrentQty(currentQty);
    inventoryLine.setTrackingNumber(trackingNumber);
    this.compute(inventoryLine, inventory);

    return inventoryLine;
  }

  public InventoryLine updateInventoryLine(InventoryLine inventoryLine, Inventory inventory) {

    StockLocation stockLocation = inventory.getStockLocation();
    Product product = inventoryLine.getProduct();

    if (product != null) {
      StockLocationLine stockLocationLine =
          Beans.get(StockLocationLineService.class)
              .getOrCreateStockLocationLine(stockLocation, product);

      if (stockLocationLine != null) {
        inventoryLine.setCurrentQty(stockLocationLine.getCurrentQty());
        inventoryLine.setRack(stockLocationLine.getRack());
      } else {
        inventoryLine.setCurrentQty(null);
        inventoryLine.setRack(null);
      }
    }

    return inventoryLine;
  }

  public InventoryLine compute(InventoryLine inventoryLine, Inventory inventory) {

    StockLocation stockLocation = inventory.getStockLocation();
    Product product = inventoryLine.getProduct();

    if (product != null) {
      StockLocationLine stockLocationLine =
          Beans.get(StockLocationLineService.class).getStockLocationLine(stockLocation, product);
      inventoryLine.setUnit(product.getUnit());
      BigDecimal gap =
          inventoryLine.getRealQty() != null
              ? inventoryLine
                  .getCurrentQty()
                  .subtract(inventoryLine.getRealQty())
                  .setScale(2, RoundingMode.HALF_EVEN)
              : BigDecimal.ZERO;
      inventoryLine.setGap(gap);

      if (stockLocationLine != null) {
        inventoryLine.setGapValue(
            stockLocationLine.getAvgPrice().multiply(gap).setScale(2, RoundingMode.HALF_EVEN));
      }
    }

    return inventoryLine;
  }

  @Transactional
  public void setInventoryLine(
      Inventory inventory,
      Product product,
      TrackingNumber trackingNumber,
      int countingType,
      BigDecimal firstCounting,
      BigDecimal secondCounting,
      BigDecimal controlCounting) {
    InventoryLine line;

    Query<InventoryLine> query = Beans.get(InventoryLineRepository.class).all();

    if (trackingNumber != null) {
      line =
          query
              .filter(
                  "self.product.id = ?1 AND self.trackingNumber.id = ?2 and self.inventory.id = ?3",
                  product.getId(),
                  trackingNumber.getId(),
                  inventory.getId())
              .fetchOne();
    } else {
      line =
          query
              .filter(
                  "self.product.id = ?1 AND self.trackingNumber is null and self.inventory.id = ?2",
                  product.getId(),
                  inventory.getId())
              .fetchOne();
    }

    if (line == null) {
      line = this.createInventoryLine(inventory, product, BigDecimal.ZERO, null, trackingNumber);
    }

    BigDecimal counting = BigDecimal.ZERO;

    switch (countingType) {
      case 1:
        counting = line.getFirstCounting() != null ? line.getFirstCounting() : BigDecimal.ZERO;
        line.setFirstCounting(counting.add(firstCounting));
        line.setFirstCountingByUser(AuthUtils.getUser());
        line.setFirstCountingDate(LocalDateTime.now());
        break;
      case 2:
        counting = line.getSecondCounting() != null ? line.getSecondCounting() : BigDecimal.ZERO;
        line.setSecondCounting(counting.add(secondCounting));
        line.setSecondCountingByUser(AuthUtils.getUser());
        line.setSecondCountingDate(LocalDateTime.now());
        break;
      case 3:
        counting = line.getControlCounting() != null ? line.getControlCounting() : BigDecimal.ZERO;
        line.setControlCounting(counting.add(controlCounting));
        line.setControlCountingByUser(AuthUtils.getUser());
        line.setControlCountingDate(LocalDateTime.now());
        break;
      default:
        break;
    }

    Beans.get(InventoryLineRepository.class).save(line);
  }
}
