package com.fdkankan.common.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

@Slf4j
public class StreamGobblerLine extends Thread {

	InputStream is;
    String type;
    OutputStream os;
    Integer lineSize;  // 多少行打印日志一次

    public StreamGobblerLine(InputStream is, String type) {
        this(is, type, null, null);
    }

    public StreamGobblerLine(InputStream is, String type, Integer lineSize) {
        this(is, type, null, lineSize);
    }

    StreamGobblerLine(InputStream is, String type, OutputStream redirect, Integer lineSize) {
        this.is = is;
        this.type = type;
        this.os = redirect;
        this.lineSize = lineSize;
    }

    public void run() {
        log.info("run StreamGobblerLine");

        InputStreamReader isr = null;
        BufferedReader br = null;
        PrintWriter pw = null;
        try {
            if (os != null)
                pw = new PrintWriter(os);

            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String line=null;
            int i = 1;
            while ( (line = br.readLine()) != null) {
                if (lineSize != null) {
                    if (i % lineSize == 0) {
                        log.info(type + "," + i +" : >" + line);
                    }
                } else {
                    log.info(type + ","  + i +" : >" + line);
                }
                i++;

            }

            if (pw != null)
                pw.flush();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally{
            try {
            	if(pw!=null)
            	{
            		 pw.close();
            	}
            	if(br!=null)
            	{
            		br.close();
            	}
            	if(isr!=null)
            	{
            		isr.close();
            	}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
