/*
 * 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.suppliermanagement.service;

import com.axelor.apps.base.db.Company;
import com.axelor.apps.base.db.Partner;
import com.axelor.apps.base.db.repo.BlockingRepository;
import com.axelor.apps.base.service.BlockingService;
import com.axelor.apps.purchase.db.PurchaseOrderLine;
import com.axelor.apps.purchase.exception.IExceptionMessage;
import com.axelor.apps.purchase.service.PurchaseOrderLineServiceImpl;
import com.axelor.apps.purchase.service.app.AppPurchaseService;
import com.axelor.apps.suppliermanagement.db.PurchaseOrderSupplierLine;
import com.axelor.apps.suppliermanagement.db.repo.PurchaseOrderSupplierLineRepository;
import com.axelor.auth.AuthUtils;
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.Context;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
import com.itextpdf.text.pdf.PdfStructTreeController.returnType;

import java.math.BigDecimal;
import com.axelor.apps.purchase.db.PurchaseOrder;
import com.axelor.apps.purchase.db.repo.PurchaseOrderLineRepository;
import com.axelor.apps.purchase.service.PurchaseOrderLineService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.math.RoundingMode;
import com.axelor.apps.base.service.app.AppBaseService;

public class PurchaseOrderSupplierLineService {

  @Inject PurchaseOrderSupplierLineRepository poSupplierLineRepo;

  @Inject protected AppPurchaseService appPurchaseService;
  
  @Inject private PurchaseOrderLineRepository purchaseOrderLineRepo;

  @Inject private PurchaseOrderLineService purchaseOrderLineService;

  @Inject protected AppBaseService appBaseService;

  @Transactional(rollbackOn = {Exception.class})
  public void accept(PurchaseOrderSupplierLine purchaseOrderSupplierLine) throws AxelorException {

    PurchaseOrderLine purchaseOrderLine = purchaseOrderSupplierLine.getPurchaseOrderLine();

    purchaseOrderLine.setEstimatedDelivDate(purchaseOrderSupplierLine.getEstimatedDelivDate());

    Partner supplierPartner = purchaseOrderSupplierLine.getSupplierPartner();
    Company company = purchaseOrderLine.getPurchaseOrder().getCompany();
    if (Beans.get(BlockingService.class)
            .getBlocking(supplierPartner, company, BlockingRepository.PURCHASE_BLOCKING)
        != null) {
      throw new AxelorException(
          TraceBackRepository.TYPE_FUNCTIONNAL,
          I18n.get(IExceptionMessage.SUPPLIER_BLOCKED),
          supplierPartner);
    }
    purchaseOrderLine.setSupplierPartner(supplierPartner);
    // set tax from tco
    purchaseOrderLine.setTaxLine(purchaseOrderSupplierLine.getTaxLine());
    purchaseOrderLine.setPrice(purchaseOrderSupplierLine.getPrice());
    purchaseOrderLine.setExTaxTotal(
        PurchaseOrderLineServiceImpl.computeAmount(
            purchaseOrderLine.getQty(), purchaseOrderLine.getPrice()));
    purchaseOrderLine.setPriceDiscounted(purchaseOrderSupplierLine.getPrice()); // sophal
    purchaseOrderSupplierLine.setStateSelect(PurchaseOrderSupplierLineRepository.STATE_ACCEPTED);
    // sophal add acceptedOn and By TCO
    purchaseOrderSupplierLine.setAcceptanceDate(appPurchaseService.getTodayDate());
    purchaseOrderSupplierLine.setAcceptedByUser(AuthUtils.getUser());;

    poSupplierLineRepo.save(purchaseOrderSupplierLine);
  }

  @Transactional(rollbackOn = {Exception.class})
  public void refuse(PurchaseOrderSupplierLine purchaseOrderSupplierLine) throws AxelorException {
    purchaseOrderSupplierLine.setStateSelect(PurchaseOrderSupplierLineRepository.STATE_NOT_ACCEPTED);
    // sophal add acceptedOn and By TCO
    purchaseOrderSupplierLine.setRefusalDate(appPurchaseService.getTodayDate());
    purchaseOrderSupplierLine.setRefusedByUser(AuthUtils.getUser());;

    poSupplierLineRepo.save(purchaseOrderSupplierLine);
  }

  public PurchaseOrderSupplierLine create(Partner supplierPartner, BigDecimal price) {

    return new PurchaseOrderSupplierLine(
        price, PurchaseOrderSupplierLineRepository.STATE_REQUESTED, supplierPartner);
  }

  @Transactional(rollbackOn = {Exception.class})
  public void savePurchaseSupplierLine(PurchaseOrderSupplierLine purchaseOrderSupplierLine){
    poSupplierLineRepo.save(purchaseOrderSupplierLine);
  }
  
   @Transactional
  public void calculateAmountsTco(PurchaseOrderSupplierLine purchaseOrderSupplierLine) throws AxelorException{
		    
    BigDecimal ExTaxTotal = BigDecimal.ZERO;
    BigDecimal taxTotal = BigDecimal.ZERO;
    BigDecimal inTaxTotal = BigDecimal.ZERO;

    ExTaxTotal = purchaseOrderSupplierLine.getPrice().multiply(purchaseOrderSupplierLine.getAvailableQty())
    .setScale(AppBaseService.DEFAULT_NB_DECIMAL_DIGITS, RoundingMode.HALF_EVEN);
    purchaseOrderSupplierLine.setExTaxTotal(ExTaxTotal);
    
    if(purchaseOrderSupplierLine.getTaxLine().getValue() != null){
      
      taxTotal = ExTaxTotal.multiply(purchaseOrderSupplierLine.getTaxLine().getValue())
      .setScale(AppBaseService.DEFAULT_NB_DECIMAL_DIGITS, RoundingMode.HALF_EVEN);
      purchaseOrderSupplierLine.setTaxTotal(taxTotal);
    }

    inTaxTotal = ExTaxTotal.add(taxTotal).setScale(AppBaseService.DEFAULT_NB_DECIMAL_DIGITS, RoundingMode.HALF_EVEN);;
    purchaseOrderSupplierLine.setInTaxTotal(inTaxTotal);
	
    poSupplierLineRepo.save(purchaseOrderSupplierLine);
  }


  @Transactional
  public void splitPurchaseOrderLinesSpecialInto2(
      PurchaseOrder purchaseOrder, PurchaseOrderLine purchaseOrderLine, BigDecimal splitQty) throws AxelorException{
		    
      BigDecimal totalQty = purchaseOrderLine.getQty();
      totalQty = totalQty.subtract(splitQty);

      if(totalQty.compareTo(BigDecimal.ZERO) > 0){ 
      
        PurchaseOrderLine newLine = purchaseOrderLineRepo.copy(purchaseOrderLine, true);
        newLine.setQty(splitQty);
        purchaseOrderLineService.compute(newLine, purchaseOrder);		
        List<PurchaseOrderSupplierLine> purchaseOrderSupplierLineList;
        purchaseOrderSupplierLineList = newLine.getPurchaseOrderSupplierLineList();	  
        if (purchaseOrderSupplierLineList != null) {
          for (PurchaseOrderSupplierLine purchaseOrderSupplierLine : purchaseOrderSupplierLineList) {
            purchaseOrderSupplierLine.setAvailableQty(splitQty);
            this.calculateAmountsTco(purchaseOrderSupplierLine);
          }
        }
        purchaseOrder.addPurchaseOrderLineListItem(newLine);

        PurchaseOrderLine newLine2 = purchaseOrderLineRepo.copy(purchaseOrderLine, true);
        newLine2.setQty(totalQty);
        purchaseOrderLineService.compute(newLine2, purchaseOrder);
        List<PurchaseOrderSupplierLine> purchaseOrderSupplierLineList2;
        purchaseOrderSupplierLineList2 = newLine2.getPurchaseOrderSupplierLineList();	  
        if (purchaseOrderSupplierLineList2 != null) {
          for (PurchaseOrderSupplierLine purchaseOrderSupplierLine2 : purchaseOrderSupplierLineList2) {
            purchaseOrderSupplierLine2.setAvailableQty(totalQty);
            this.calculateAmountsTco(purchaseOrderSupplierLine2);
          }
        }
        purchaseOrder.addPurchaseOrderLineListItem(newLine2);
        
          
        purchaseOrder.removePurchaseOrderLineListItem(purchaseOrderLine);			 
        
      }   
  }


  public  Map<String, BigDecimal>  compute(PurchaseOrderSupplierLine line) {
   
       HashMap<String, BigDecimal> map = new HashMap<>();
      if (line == null
          || line.getPrice() == null
          || line.getTaxLine() == null) {
        return map;
      }


      BigDecimal exTaxTotal = line.getPrice().multiply(line.getAvailableQty()) ;
      BigDecimal taxRate = line.getTaxLine().getValue();
      BigDecimal taxTotal = exTaxTotal.multiply(taxRate);
      BigDecimal inTaxTotal = exTaxTotal.add(taxTotal);
      map.put("exTaxTotal", exTaxTotal);
      map.put("taxTotal", taxTotal);
      map.put("inTaxTotal", inTaxTotal);
      return map;
    
  }

}
