/*
 * Copyright © 2019 by Data Virtuality GmbH
 */
package org.teiid.translator.jdbc;

import java.io.IOException;
import java.io.Reader;

/**
 * @author Roman Pedchenko
 * @date 2019.11.23
 */
public interface ReplaceNullCharsIntf {
    String isReplaceNullCharsWith();

    class Util {
        private static final String NULLCHAR_STRING = "\0";
        private static final String DEFAULT = " ";

        public static String replaceNullCharsIfNeeded(ReplaceNullCharsIntf self, Object object) {
            String string = null;
            if (object != null)
                string = object.toString();
            String replaceNullCharsWith = self.isReplaceNullCharsWith();
            if (replaceNullCharsWith == null)
                replaceNullCharsWith = DEFAULT;
            if (NULLCHAR_STRING.equals(replaceNullCharsWith) || string == null)
                return string;
            return string.replace(NULLCHAR_STRING, replaceNullCharsWith);
        }

        public static Reader nullCharStream(ReplaceNullCharsIntf self, final Reader stream) {
            String replaceNullCharsWith = self.isReplaceNullCharsWith();
            if (replaceNullCharsWith == null)
                replaceNullCharsWith = DEFAULT;
            final char repl = replaceNullCharsWith.charAt(0);
            return new Reader() {
                @Override
                public int read(char[] cbuf, int off, int len) throws IOException {
                    int res = stream.read(cbuf, off, len);
                    if (res > 0)
                        for (int i = 0; i < res; i++) {
                            int p = off + i;
                            if (cbuf[p] == 0)
                                cbuf[p] = repl;
                        }
                    return res;
                }

                @Override
                public void close() throws IOException {
                    stream.close();
                }
            };
        }
    }
}
