/**
 * Copyright © 2024 by Data Virtuality GmbH
 */
package org.teiid.core.types.basic;

import org.teiid.core.plugin.CorePlugin;
import org.teiid.core.types.ArrayImpl;
import org.teiid.core.types.TransformationException;

/**
 * @author Mate Simovic
 * @date 2024.08.09
 */
public class StringToArrayTransform extends ObjectToAnyTransform {

	public static final StringToArrayTransform INSTANCE = new StringToArrayTransform();

	public StringToArrayTransform() {
		super(Object.class);
	}

    @Override
    public Object transform(Object value, Class<?> targetType) throws TransformationException {
    	if (value == null) {
    		return null;
    	}
		if (!(value instanceof String)) {
			Object[] params = new Object[] { getSourceType(), targetType, value};
			throw new TransformationException(CorePlugin.Event.TEIID10076, CorePlugin.Util.gs(CorePlugin.Event.TEIID10076, params));
		}
		
		return super.transform(arrayFromString((String) value), targetType);
    }

	/**
	 * @param value eg. "[1,2,3,4]"
	 */
	private ArrayImpl arrayFromString(String value) {
		if (value == null) {
			return null;
		}
		value = value.trim();
		value = value.substring(1, value.length() - 1).trim(); // remove the [ from the beginning and ] from the end
		return new ArrayImpl(value.split(","));
	}
}
