package ma.glasnost.orika.impl.generator.specification;

import static java.lang.String.format;
import static ma.glasnost.orika.impl.generator.SourceCodeContext.statement;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.generator.SourceCodeContext;
import ma.glasnost.orika.impl.generator.VariableRef;
import ma.glasnost.orika.metadata.FieldMap;
import ma.glasnost.orika.metadata.Property;

public class Convert extends AbstractSpecification {

    public Convert(MapperFactory mapperFactory) {
        super(mapperFactory);
    }

    public boolean appliesTo(FieldMap fieldMap) {
        return fieldMap.getConverterId() != null || mapperFactory.getConverterFactory().canConvert(fieldMap.getAType(), fieldMap.getBType());
    }

    public String generateEqualityTestCode(VariableRef source, VariableRef destination, Property inverseProperty, SourceCodeContext code) {
        if (source.type().isPrimitive() || destination.type().isPrimitive()) {
            return format("(%s == %s.convert(%s, %s))", destination.asWrapper(), code.usedConverter(source.getConverter()), source.asWrapper(), code.usedType(destination));
        } else {
            return format("(%s != null && %s.equals(%s.convert(%s, %s)))", source, destination, code.usedConverter(source.getConverter()), source.asWrapper(), code.usedType(destination));
        }
        
    }

    public String generateMappingCode(VariableRef source, VariableRef destination, Property inverseProperty, SourceCodeContext code) {
        
        String statement = destination.assign("%s.convert(%s, %s)", code.usedConverter(source.getConverter()), source.asWrapper(), code.usedType(destination));
        
        if (source.isPrimitive()) {
            return statement(statement);
        } else {
            return statement(source.ifNotNull() + statement);
        }
    }
    
}

@@ -1674,32 +1674,126 @@
 ion));%0A        %0A
+        boolean shouldSetNull = code.shouldMapNulls() && !destination.isPrimitive();%0A        %0A
         if (sour
@@ -1862,32 +1862,125 @@
        %7D else %7B%0A
+        %09String elseSetNull   = shouldSetNull ? (%22else %22 + destination.assign(%22null%22)) : %22%22;%0A
             retu
@@ -2015,32 +2015,57 @@
 l() + statement)
+ + statement(elseSetNull)
 ;%0A        %7D%0A    

Fix mapNulls, code generation for the conversion cases does not supported mapNulls