package weaver.interfaces.htsc.download;

import weaver.general.BaseBean;

import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.StreamingOutput;
import java.io.*;
import java.util.zip.ZipInputStream;

public class FileStream implements StreamingOutput {

    private  String filePath;
    private String iszip;
    public FileStream(String filePath,String iszip) {
        this.filePath = filePath;
        this.iszip = iszip;
    }

    public void write(OutputStream output) throws IOException, WebApplicationException {
        BufferedInputStream inputStream = null;
        BaseBean bb = new BaseBean();
        try {
            if (filePath != null && !filePath.equals(""))
            {
                File file = new File(filePath);
                if(!file.exists())
                {
                    throw  new WebApplicationException(404);
                }
                if (iszip.equals("1")) {
                    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file));
                    if (zipInputStream.getNextEntry() != null) {
                        inputStream = new BufferedInputStream(zipInputStream);
                    }
                } else {
                    inputStream = new BufferedInputStream(new FileInputStream(file));
                }

                byte[] buffer = new byte[4096];
                int n = 0;
                while (-1 != (n = inputStream.read(buffer))) {
                    output.write(buffer, 0, n);
                }

                output.flush();
                inputStream.close();
                output.close();
            }
        }catch (IOException e){
            bb.writeLog("e:"+e);
            throw new IOException(e);
        }finally {
            if(inputStream !=null){
                inputStream.close();
            }
            if(output !=null){
                output.close();
            }
        }
    }
}
