/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2020 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.base.service;

import com.axelor.apps.base.db.Product;
import com.axelor.db.JPA;
import com.google.inject.servlet.RequestScoped;
import javax.persistence.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RequestScoped
public class SophalServiceImpl implements SophalService {

  protected Logger log = LoggerFactory.getLogger(getClass());

  @Override
  public String GenerateCode(Product product) {

    String num;
    String result;
    String var;

    if (product.getUnitCodeSelect() != null) {
      var =
          product.getFamilleProduit().getCode()
              + product.getSousFamilleProduit().getCode()
              + product.getUnitCodeSelect();
    } else {
      var =
          product.getFamilleProduit().getCode() + product.getSousFamilleProduit().getCode() + "00";
    }

    if (product.getCode() == null) {
      Query q =
          JPA.em()
              .createQuery(
                  "select self.code FROM Product as self WHERE  self.codeCreated = ?1 AND self.code LIKE  ?2  ORDER BY self.code DESC",
                  String.class);
      q.setParameter(1, true);
      q.setParameter(2, var + "%");

      if (q.getResultList().size() == 0) {
        result = null;
      } else {
        result = (String) q.getResultList().get(0);
      }

      if (result != null) {

        String arr[] = result.split(var);
        String nbrString = arr[1];
        int nbrInt = Integer.parseInt(nbrString);

        nbrInt = nbrInt + 1;
        num = Integer.toString(nbrInt);

        String padding = "000".substring(num.length()) + num;
        result = var + padding;

      } else {

        result = var + "001";
      }

    } else {
      result = product.getCode();
    }

    return result;
  }
}
