package com.qmth.jkserver.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.qmth.jkserver.constant.SystemConstant;
import org.apache.commons.io.ByteOrderMark;
import org.apache.commons.io.input.BOMInputStream;
import org.apache.commons.lang3.StringUtils;

public class FileData {

    private BufferedReader reader;

    private String splite;

    private String line;

    private String[] datas;

    public FileData(String filename, String splite) throws IOException {
    	BOMInputStream bomIn = new BOMInputStream(new FileInputStream(filename), false,ByteOrderMark.UTF_8);
    	String charset = bomIn.hasBOM() ? bomIn.getBOMCharsetName() : SystemConstant.CHARSET_NAME;
    	this.reader = new BufferedReader(new InputStreamReader(bomIn,charset));
        this.splite = splite;
        this.line = null;
    }
    
    public FileData(File file, String splite) throws IOException {
    	BOMInputStream bomIn = new BOMInputStream(new FileInputStream(file), false,ByteOrderMark.UTF_8);
    	String charset = bomIn.hasBOM() ? bomIn.getBOMCharsetName() : SystemConstant.CHARSET_NAME;
    	this.reader = new BufferedReader(new InputStreamReader(bomIn,charset));
        this.splite = splite;
        this.line = null;
    }
    
    public FileData(InputStream inputStream, String splite) throws IOException {
    	BOMInputStream bomIn = new BOMInputStream(inputStream, false,ByteOrderMark.UTF_8);
    	String charset = bomIn.hasBOM() ? bomIn.getBOMCharsetName() : SystemConstant.CHARSET_NAME;
    	this.reader = new BufferedReader(new InputStreamReader(bomIn, charset));
        this.splite = splite;
        this.line = null;
    }
    
    public String getData(int column) {
        if (datas != null && datas.length > column) {
            return datas[column];
        } else {
            return null;
        }
    }

    public boolean nextLine() {
        try {
            this.line = reader.readLine();
            //此处不能够去除空白字符串，否则会导致可变的数组长度
            this.datas = StringUtils.splitByWholeSeparatorPreserveAllTokens(line, splite);
        } catch (Exception e) {
        }
        return line != null;
    }

    public int getColumnCount() {
        return datas != null ? datas.length : 0;
    }

    public String[] getDatas() {
        return datas;
    }
  
    public String getLine() {
        if (line != null) {
            return line;
        } else {
            return null;
        }
    }

    public void close() {
        try {
            reader.close();
        } catch (Exception e) {
        }
    }
    
    
//    public static void main(String[] args) {
//    	String string = "1~核心能力测评~1~021711006180~高飞龙~201701~语文素养与应用~2018-02-01 09:36:27~1~核心能力测评~1~";
//		System.out.println(StringUtils.split(string,"~").length);
//		System.out.println(StringUtils.splitByWholeSeparator(string,"~").length);
//	}
}
