package com.ansj.dic;

import org.ansj.dic.DicReader;
import org.ansj.dic.PathToStream;
import org.ansj.exception.LibraryException;
import org.nlpcn.commons.lang.util.logging.Log;
import org.nlpcn.commons.lang.util.logging.LogFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ResourceBundle;
import java.util.Vector;

/**
 * @author dyp
 */
public class File2Stream extends PathToStream {
    private static final Log LOG = LogFactory.getLog(org.ansj.dic.impl.File2Stream.class);

    public File2Stream() {
    }

    public InputStream toStream(String path) {

        File file = new File(path);
        if (file.exists() && file.canRead()) {
            try {
                return (InputStream)(file.isDirectory() ? this.multiple(path) : new FileInputStream(file));
            } catch (Exception var4) {
                throw new LibraryException(var4);
            }
        } else {
            throw new LibraryException(" path :" + path + " file:" + file.getAbsolutePath() + " not found or can not to read");
        }
    }

    private InputStream multiple(String path) throws FileNotFoundException {
        File[] libs = new File[0];
        File file = new File(path);
        if (file.exists() && file.canRead()) {
            if (file.isFile()) {
                libs = new File[]{file};
            } else if (file.isDirectory()) {
                File[] files = file.listFiles(new FileFilter() {
                    public boolean accept(File file) {
                        return file.canRead() && !file.isHidden() && !file.isDirectory();
                    }
                });
                if (files != null && files.length > 0) {
                    libs = files;
                }
            }
        }

        if (libs.length == 0) {
            throw new LibraryException("not find any file in path : " + path);
        } else if (libs.length == 1) {
            return new FileInputStream(libs[0]);
        } else {
            Vector<InputStream> vector = new Vector(libs.length);

            for(int i = 0; i < libs.length; ++i) {
                vector.add(new FileInputStream(libs[i]));
                if (i < libs.length - 1) {
                    vector.add(new ByteArrayInputStream("\n".getBytes(StandardCharsets.UTF_8)));
                }
            }

            return new SequenceInputStream(vector.elements());
        }
    }
}
