package com.capgemini.reports.builder;

import com.capgemini.reports.database.javabean.enumeration.ReportCriteriaEnum;
import com.capgemini.reports.definition.r01report.ExecutionR01;
import com.capgemini.reports.exceptions.InsufficientParametersException;
import com.capgemini.reports.reports.parameters.EffectivityDate;
import com.capgemini.reports.reports.parameters.Generics;
import com.capgemini.reports.reports.parameters.MonoMulti;
import com.capgemini.reports.reports.parameters.ProductUnit;
import com.google.common.base.Joiner;

import java.util.Map;

/** Reconstructs a R01 report from BOM parameters. Generic parameters are optional. */
public class R01Builder implements ReportBuilder {

    @Override
    public ExecutionR01 build(Map<ReportCriteriaEnum, String> data) throws InsufficientParametersException {
        // Get the request raw data
        String product = data.get(ReportCriteriaEnum.PRODUCT);
        String unitStr = data.get(ReportCriteriaEnum.UNIT);
        String monoMultiStr = data.get(ReportCriteriaEnum.MONO_MULTI);
        String generic = data.get(ReportCriteriaEnum.GENERIC);
        String genericAssemb = data.get(ReportCriteriaEnum.GENERIC_ASSEMB);
        String effectivityStr = data.get(ReportCriteriaEnum.EFFECTIVITY_DATE);
        String superModelStr = data.get(ReportCriteriaEnum.SUPERMODEL);


        // Check presence of all required args
        if (product == null || unitStr == null || monoMultiStr == null) {
            String dataStr = Joiner.on('|').withKeyValueSeparator("=").useForNull("null").join(data);
            throw new InsufficientParametersException("Missing parameter for R01 launch. Obtained: " + dataStr);
        }
        int unit;
        try {
            unit = Integer.parseInt(unitStr);
        } catch (NumberFormatException e) {
            throw new InsufficientParametersException("Unit parameter is not an int: " + unitStr, e);
        }
        ProductUnit aProductUnit = new ProductUnit(product, unit);
        Generics aGeneric = new Generics(aProductUnit, generic, genericAssemb);
        MonoMulti aMonoMulti = MonoMulti.build(monoMultiStr);
        EffectivityDate anEffectivity = new EffectivityDate(effectivityStr);
        boolean isSuperModelBOM = Boolean.parseBoolean(superModelStr);

        // Build the report
        return new ExecutionR01(aProductUnit, aGeneric, aMonoMulti, anEffectivity, isSuperModelBOM);
    }

}
