/*
 * 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.account.db.Move;
import com.axelor.apps.account.exception.IExceptionMessage;
import com.axelor.apps.base.db.Batch;
import com.axelor.apps.stock.db.StockMove;
import com.axelor.apps.stock.db.repo.StockMoveRepository;
import com.axelor.apps.supplychain.db.SupplychainBatch;
import com.axelor.apps.supplychain.db.repo.SupplychainBatchRepository;
import com.axelor.apps.supplychain.service.AccountingCutOffServiceImpl;
import com.axelor.apps.supplychain.service.batch.SupplychainBatchService;
import com.axelor.common.ObjectUtils;
import com.axelor.exception.AxelorException;
import com.axelor.exception.service.TraceBackService;
import com.axelor.i18n.I18n;
import com.axelor.inject.Beans;
import com.axelor.meta.schema.actions.ActionView;
import com.axelor.rpc.ActionRequest;
import com.axelor.rpc.ActionResponse;
import com.google.common.base.Joiner;
import com.google.inject.Singleton;
import java.util.List;
import java.util.stream.Collectors;

@Singleton
public class SupplychainBatchController {

  public void invoiceOutgoingStockMoves(ActionRequest request, ActionResponse response) {
    SupplychainBatch supplychainBatch = request.getContext().asType(SupplychainBatch.class);
    supplychainBatch = Beans.get(SupplychainBatchRepository.class).find(supplychainBatch.getId());
    Batch batch =
        Beans.get(SupplychainBatchService.class).invoiceOutgoingStockMoves(supplychainBatch);
    response.setFlash(batch.getComments());
    response.setReload(true);
  }

  public void invoiceOrders(ActionRequest request, ActionResponse response) {
    SupplychainBatch supplychainBatch = request.getContext().asType(SupplychainBatch.class);
    supplychainBatch = Beans.get(SupplychainBatchRepository.class).find(supplychainBatch.getId());
    Batch batch = Beans.get(SupplychainBatchService.class).invoiceOrders(supplychainBatch);
    response.setFlash(batch.getComments());
    response.setReload(true);
  }

  public void accountingCutOff(ActionRequest request, ActionResponse response) {
    SupplychainBatch supplychainBatch = request.getContext().asType(SupplychainBatch.class);
    supplychainBatch = Beans.get(SupplychainBatchRepository.class).find(supplychainBatch.getId());
    Batch batch = Beans.get(SupplychainBatchService.class).accountingCutOff(supplychainBatch);
    response.setFlash(batch.getComments());
    response.setReload(true);
  }

  public void generateMove(ActionRequest request, ActionResponse response) throws AxelorException {
    StockMove stockMove = request.getContext().asType(StockMove.class);
    stockMove = Beans.get(StockMoveRepository.class).find(stockMove.getId());
    Move move = Beans.get(AccountingCutOffServiceImpl.class).generateStockAccountMove(stockMove);
    response.setView(
        ActionView.define(stockMove.getStockMoveSeq())
            .model(Move.class.getName())
            .add("form", "move-form")
            .add("grid", "move-grid")
            .param("forceTitle", "true")
            .context("_showRecord", move.getId().toString())
            .domain("self.id = " + move.getId())
            .map());
  }

  public void massGenerationMove(ActionRequest request, ActionResponse response) {
    try {

      @SuppressWarnings("unchecked")
      List<Long> ids =
          (List)
              (((List) request.getContext().get("_ids"))
                  .stream()
                  .filter(ObjectUtils::notEmpty)
                  .map(input -> Long.parseLong(input.toString()))
                  .collect(Collectors.toList()));
      List<Long> moveList = Beans.get(AccountingCutOffServiceImpl.class).massGenerationMove(ids);

      if (moveList != null && !moveList.isEmpty()) {
        response.setView(
            ActionView.define(I18n.get(IExceptionMessage.MOVE_TEMPLATE_3))
                .model(Move.class.getName())
                .add("grid", "move-grid")
                .add("form", "move-form")
                .domain("self.id in (" + Joiner.on(",").join(moveList) + ")")
                .map());
      }
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }

  public void generateInventoryLineMove(ActionRequest request, ActionResponse response) {
    try {

      @SuppressWarnings("unchecked")
      List<Long> ids =
          (List)
              (((List) request.getContext().get("_ids"))
                  .stream()
                  .filter(ObjectUtils::notEmpty)
                  .map(input -> Long.parseLong(input.toString()))
                  .collect(Collectors.toList()));
      List<Long> moveList =
          Beans.get(AccountingCutOffServiceImpl.class).massGenerationInventoryLineMove(ids);

      if (moveList != null && !moveList.isEmpty()) {
        response.setView(
            ActionView.define(I18n.get(IExceptionMessage.MOVE_TEMPLATE_3))
                .model(Move.class.getName())
                .add("grid", "move-grid")
                .add("form", "move-form")
                .domain("self.id in (" + Joiner.on(",").join(moveList) + ")")
                .map());
      }
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }
}
