/*
 * 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.supplychain.web;

import com.axelor.apps.base.db.Company;
import com.axelor.apps.sale.db.SaleOrder;
import com.axelor.apps.stock.db.StockLocation;
import com.axelor.apps.stock.db.StockMove;
import com.axelor.apps.stock.db.StockMoveLine;
import com.axelor.apps.stock.db.repo.StockMoveRepository;
import com.axelor.apps.supplychain.db.SupplyChainConfig;
import com.axelor.apps.supplychain.exception.IExceptionMessage;
import com.axelor.apps.supplychain.service.SaleOrderReservedQtyService;
import com.axelor.apps.supplychain.service.SaleOrderStockService;
import com.axelor.apps.supplychain.service.StockConfigService;
import com.axelor.apps.supplychain.service.StockMoveServiceSupplychain;
import com.axelor.apps.supplychain.service.StockMoveServiceSupplychainImpl;
import com.axelor.apps.supplychain.service.app.AppSupplychainService;
import com.axelor.apps.supplychain.service.config.SupplyChainConfigService;
import com.axelor.db.JPA;
import com.axelor.exception.AxelorException;
import com.axelor.exception.db.repo.TraceBackRepository;
import com.axelor.exception.service.TraceBackService;
import com.axelor.i18n.I18n;
import com.axelor.inject.Beans;
import com.axelor.rpc.ActionRequest;
import com.axelor.rpc.ActionResponse;

import java.lang.invoke.MethodHandles;
import java.util.List;
import java.util.Optional;

import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StockMoveController {
  private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

  public void addSubLines(ActionRequest request, ActionResponse response) {
    try {
      StockMove stockMove = request.getContext().asType(StockMove.class);
      response.setValue(
          "stockMoveLineList",
          Beans.get(StockMoveServiceSupplychain.class)
              .addSubLines(stockMove.getStockMoveLineList()));
    } catch (Exception e) {
      TraceBackService.trace(response, e);
      response.setReload(true);
    }
  }

  public void removeSubLines(ActionRequest request, ActionResponse response) {
    try {
      StockMove stockMove = request.getContext().asType(StockMove.class);
      response.setValue(
          "stockMoveLineList",
          Beans.get(StockMoveServiceSupplychain.class)
              .removeSubLines(stockMove.getStockMoveLineList()));
    } catch (Exception e) {
      TraceBackService.trace(response, e);
      response.setReload(true);
    }
  }

  public void verifyProductStock(ActionRequest request, ActionResponse response) {
    try {
      StockMove stockMove = request.getContext().asType(StockMove.class);
      if (stockMove.getPickingIsEdited() && !stockMove.getAvailabilityRequest()) {
        response.setValue("availabilityRequest", true);
        response.setFlash(
            I18n.get(IExceptionMessage.STOCK_MOVE_AVAILABILITY_REQUEST_NOT_UPDATABLE));
        return;
      }
      Beans.get(StockMoveServiceSupplychain.class).verifyProductStock(stockMove);
    } catch (Exception e) {
      TraceBackService.trace(response, e);
      response.setValue("availabilityRequest", false);
    }
  }

  /**
   * Called from stock move form view, on available qty boolean change. Only called if the user
   * accepted to allocate everything. Call {@link SaleOrderStockService#findSaleOrder(StockMove)} to
   * fetch related sale order then {@link SaleOrderReservedQtyService#allocateAll(SaleOrder)} to
   * allocate everything in sale order.
   *
   * @param request
   * @param response
   */
  public void allocateAll(ActionRequest request, ActionResponse response) {
    try {
      StockMove stockMove = request.getContext().asType(StockMove.class);
      Company company = stockMove.getCompany();
      if (company == null) {
        return;
      }

      SupplyChainConfig supplyChainConfig =
          Beans.get(SupplyChainConfigService.class).getSupplyChainConfig(company);
      if (!Beans.get(AppSupplychainService.class).getAppSupplychain().getManageStockReservation()
          || !stockMove.getAvailabilityRequest()
          || !supplyChainConfig.getAutoAllocateOnAvailabilityRequest()) {
        return;
      }
      Optional<SaleOrder> saleOrderOpt =
          Beans.get(SaleOrderStockService.class).findSaleOrder(stockMove);
      if (saleOrderOpt.isPresent()) {
        Beans.get(SaleOrderReservedQtyService.class).allocateAll(saleOrderOpt.get());
      }
    } catch (Exception e) {
      TraceBackService.trace(response, e);
      response.setReload(true);
    }
  }

  public void splitInto2Same(ActionRequest request, ActionResponse response) {
    StockMove stockMove = request.getContext().asType(StockMove.class);
    List<StockMoveLine> modifiedStockMoveLineList = stockMove.getStockMoveLineList();

    stockMove = Beans.get(StockMoveRepository.class).find(stockMove.getId());

    try {
      StockMove newStockMove =
          Beans.get(StockMoveServiceSupplychainImpl.class)
              .splitInto2SameMove(stockMove, modifiedStockMoveLineList);

      if (newStockMove == null) {
        response.setFlash(I18n.get(""));
      } else {
        response.setReload(true);
      }
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }

    public void checkIfQuarantine(ActionRequest request, ActionResponse response)
      throws AxelorException {

    StockMove stockMoveFromRequest = request.getContext().asType(StockMove.class);

    StockMove stockMove = Beans.get(StockMoveRepository.class).find(stockMoveFromRequest.getId());
    Query sql =
        JPA.em()
            .createNativeQuery(
                "SELECT LINE.ID"+
" FROM STOCK_STOCK_MOVE_LINE LINE LEFT JOIN STOCK_STOCK_LOCATION_LINE LOCATION_LINE ON LINE.TRACKING_NUMBER = LOCATION_LINE.TRACKING_NUMBER and LINE.product = LOCATION_LINE.product"+
" where LOCATION_LINE.DETAILS_STOCK_LOCATION = ?1 AND LOCATION_LINE.CONFORMITY_SELECT != 2 AND LOCATION_LINE.CONFORMITY_SELECT != 5 AND LINE.STOCK_MOVE = ?2");
    sql.setParameter(1, stockMove.getFromStockLocation().getId());
    sql.setParameter(2, stockMove.getId());
    logger.debug("sql.getResultList().size()",sql.getResultList().size());
    if (sql.getResultList().size() > 0) {
      throw new AxelorException(
          stockMove,
          TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
          "vous avez une ligne en etat qurantaine");
    }
  }

  public void checkIfDiffNonCompliant(ActionRequest request, ActionResponse response)
      throws AxelorException {
          
      StockMove stockMoveFromContext = request.getContext().asType(StockMove.class);
      StockMove stockMove = Beans.get(StockMoveRepository.class).find(stockMoveFromContext.getId());
      Query sql =
          JPA.em()
              .createNativeQuery(
                  "SELECT LINE.ID"  +
                  " FROM STOCK_STOCK_MOVE_LINE LINE LEFT JOIN STOCK_STOCK_LOCATION_LINE LOCATION_LINE ON LINE.TRACKING_NUMBER = LOCATION_LINE.TRACKING_NUMBER and LINE.product = LOCATION_LINE.product" +
                  " where LOCATION_LINE.DETAILS_STOCK_LOCATION = ?1 AND LOCATION_LINE.CONFORMITY_SELECT != 3 AND LINE.STOCK_MOVE = ?2");
      sql.setParameter(1, stockMove.getFromStockLocation().getId());
      sql.setParameter(2, stockMove.getId());
      logger.debug("sql.getResultList().size()",sql.getResultList().size());
      if (sql.getResultList().size() > 0) {
        throw new AxelorException(
            stockMove,
            TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
            "vous avez une ligne differente de NC");
    }
  }

  public void checkIfNonCompliant(ActionRequest request, ActionResponse response)
      throws AxelorException {
          
      StockMove stockMoveFromContext = request.getContext().asType(StockMove.class);
      StockMove stockMove = Beans.get(StockMoveRepository.class).find(stockMoveFromContext.getId());
      Query sql =
          JPA.em()
              .createNativeQuery(
                  "SELECT LINE.ID"  +
                  " FROM STOCK_STOCK_MOVE_LINE LINE LEFT JOIN STOCK_STOCK_LOCATION_LINE LOCATION_LINE ON LINE.TRACKING_NUMBER = LOCATION_LINE.TRACKING_NUMBER and LINE.product = LOCATION_LINE.product" +
                  " where LOCATION_LINE.DETAILS_STOCK_LOCATION = ?1 AND LOCATION_LINE.CONFORMITY_SELECT = 3 AND LINE.STOCK_MOVE = ?2");
      sql.setParameter(1, stockMove.getFromStockLocation().getId());
      sql.setParameter(2, stockMove.getId());
      logger.debug("sql.getResultList().size()",sql.getResultList().size());
      if (sql.getResultList().size() > 0) {
        throw new AxelorException(
            stockMove,
            TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
            "vous avez une ligne NC");
    }
  }

  public void checkIfNonConformityTag(ActionRequest request, ActionResponse response)
      throws AxelorException {
          
      StockMove stockMoveFromContext = request.getContext().asType(StockMove.class);
      StockMove stockMove = Beans.get(StockMoveRepository.class).find(stockMoveFromContext.getId());
      Query sql =
          JPA.em()
              .createNativeQuery(
                  "SELECT LINE.ID"  +
                  " FROM STOCK_STOCK_MOVE_LINE LINE LEFT JOIN STOCK_STOCK_LOCATION_LINE LOCATION_LINE ON LINE.TRACKING_NUMBER = LOCATION_LINE.TRACKING_NUMBER and LINE.product = LOCATION_LINE.product" +
                  " where LOCATION_LINE.DETAILS_STOCK_LOCATION = ?1 AND LOCATION_LINE.is_conform_tag is not true AND LINE.STOCK_MOVE = ?2");
      sql.setParameter(1, stockMove.getFromStockLocation().getId());
      sql.setParameter(2, stockMove.getId());
      logger.debug("sql.getResultList().size {}",sql.getResultList().size());
      if (sql.getResultList().size() > 0) {
        throw new AxelorException(
            stockMove,
            TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
            "vous avez une ligne non étiqueté");
    }
  }

}
