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

import org.teiid.core.plugin.CorePlugin;
import org.teiid.core.types.BlobType;
import org.teiid.core.types.DataTypeManager;
import org.teiid.core.types.TransformationException;
import org.teiid.core.util.ObjectConverterUtil;

import java.io.IOException;
import java.sql.SQLException;

/**
 * @author Adil Hamiani
 * @date 2022.08.25
 */
public class BlobToStringTransform extends AnyToStringTransform {

    public BlobToStringTransform() {
        super(DataTypeManager.DefaultDataClasses.BLOB);
    }

    public Object transformDirect(Object value) throws TransformationException {
        BlobType source = (BlobType) value;
        try {
            byte[] bytes = ObjectConverterUtil.convertToByteArray(source.getBinaryStream(), DataTypeManager.MAX_VARBINARY_BYTES, true);
            return new String(bytes);
        } catch (SQLException e) {
            throw new TransformationException(CorePlugin.Event.TEIID10080, e, CorePlugin.Util.gs(CorePlugin.Event.TEIID10080, new Object[]{getSourceType().getName(), getTargetType().getName()}));
        } catch (IOException e) {
            throw new TransformationException(CorePlugin.Event.TEIID10080, e, CorePlugin.Util.gs(CorePlugin.Event.TEIID10080, new Object[]{getSourceType().getName(), getTargetType().getName()}));
        }
    }


    public boolean isExplicit() {
        return true;
    }
}
