package com.capgemini.reports.builder;

import com.capgemini.reports.database.javabean.enumeration.ReportCriteriaEnum;
import com.capgemini.reports.definition.r07report.ExecutionR07;
import com.capgemini.reports.exceptions.InsufficientParametersException;
import com.capgemini.reports.reports.parameters.Generics;
import com.capgemini.reports.reports.parameters.ProductUnit;
import com.google.common.base.Joiner;

import java.util.Map;

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

    @Override
    public ExecutionR07 build(Map<ReportCriteriaEnum, String> data) throws InsufficientParametersException {
        // Get the request raw data
        String product = data.get(ReportCriteriaEnum.PRODUCT);
        String unitStr1 = data.get(ReportCriteriaEnum.UNIT_CONFIGURATION_1);
        String unitStr2 = data.get(ReportCriteriaEnum.UNIT_CONFIGURATION_2);
        String generic = data.get(ReportCriteriaEnum.GENERIC);
        String genericAssemb = data.get(ReportCriteriaEnum.GENERIC_ASSEMB);

        // Check presence of all required args
        if (product == null || unitStr1 == null || unitStr2 == null) {
            String dataStr = Joiner.on('|').withKeyValueSeparator("=").useForNull("null").join(data);
            throw new InsufficientParametersException("Missing parameter for R07 launch. Obtained: " + dataStr);
        }
        int unit1;
        try {
            unit1 = Integer.parseInt(unitStr1);
        } catch (NumberFormatException e) {
            throw new InsufficientParametersException("Unit parameter 1 is not an int: " + unitStr1, e);
        }
        int unit2;
        try {
            unit2 = Integer.parseInt(unitStr2);
        } catch (NumberFormatException e) {
            throw new InsufficientParametersException("Unit parameter 2 is not an int: " + unitStr2, e);
        }
        ProductUnit aProductUnit1 = new ProductUnit(product, unit1);
        ProductUnit aProductUnit2 = new ProductUnit(product, unit2);
        Generics gen1 = new Generics(aProductUnit1, generic, genericAssemb); // only difference should be unit #
        Generics gen2 = new Generics(aProductUnit2, generic, genericAssemb); // Generics are optional

        // Build the report
        return new ExecutionR07(gen1, gen2);
    }

}
