package com.cnd3b.utility.uploadfile;


import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.StringTokenizer;

public class UploadFile implements HttpSessionBindingListener {
    //文件名称
    private String filename = null;
    //目录地址
    private String directoryname = ".";
    //字节数组输出流
    private ByteArrayOutputStream stream = null;
    private String postfix = null;

    /**
     * 构造函数
     *
     * @param filename 文件名称
     * @param stream
     */
    public UploadFile(String filename, String filetype, ByteArrayOutputStream stream) {
        this.filename = filename;
        this.stream = stream;
        this.postfix = filename.substring(filename.lastIndexOf(".") + 1);
        if (!"".equals(filetype)) {
            postfix = filetype;
        }

    }

    /**
     * 设置文件名称
     *
     * @param filename
     */
    public void setFileName(String filename) {
        this.filename = filename;
    }

    /**
     * 获取文件名称
     *
     * @return
     */
    public String getFileName() {
        return this.filename;
    }


    /**
     * 获取文件名全称（目录+文件名）
     *
     * @return
     */
    public String getAbsoluteFileName() {
        return this.getDirectoryName() + File.separator + this.getFileName();
    }

    /**
     * 设置文件存放目录
     *
     * @param directoryname
     * @throws IOException
     */
    public void setDirectoryName(String directoryname) throws IOException {
        if (this.getDirectoryName() != null && !this.getDirectoryName().equals(".") && this.getFileName() != null && directoryname != null && !directoryname.equals(this.getDirectoryName())) {
            File file = new File(directoryname);
            if (!file.exists()) {
                file.mkdirs();
            }
        }
        this.directoryname = directoryname;
    }

    /**
     * 获取文件存放目录
     *
     * @return
     */
    public String getDirectoryName() {
        return this.directoryname;
    }


    private void deleteFile() throws IOException {
        File file = new File(this.getAbsoluteFileName());
        if (file.exists()) {
            file.delete();
        }
    }

    public void writeToDisk() throws IOException {
        if (this.stream.size() > 0) {
            String filename = createFileName(this.getFileName());
            this.setFileName(filename);
            File file = new File(this.getDirectoryName());
            if (!file.exists()) {
                file.mkdirs();
            }

            if (!file.isDirectory()) {
                throw new IllegalArgumentException("Not filename directory: " + this.getDirectoryName());
            }

            if (!file.canWrite()) {
                throw new IllegalArgumentException("Not writable: " + this.getDirectoryName());
            }

            //(new StringBuilder()).append(file).append(File.separator).append(filename);

            filename = createMD5FileName(file.getName()) + "." + this.postfix;
            this.setFileName(filename);
            filename = file + File.separator + filename;
            FileOutputStream stream = new FileOutputStream(new File(filename));
            this.stream.writeTo(stream);
            stream.close();

            this.stream.close();
            this.stream = null;
        }
    }


    /**
     * 去除文件名称中的多余字符：空格、换行符、回车符等
     *
     * @param filename
     * @return
     */
    private static String createFileName(String filename) {
        StringBuilder newfilename = null;
        StringTokenizer stringTokenizer = new StringTokenizer(filename.trim());
        while (stringTokenizer.hasMoreTokens()) {
            if (newfilename == null) {
                newfilename = new StringBuilder(stringTokenizer.nextToken());
            } else {
                newfilename.append(stringTokenizer.nextToken());
            }
        }
        return newfilename.toString();
    }

    private static String createMD5FileName(String filename) throws IOException {
        String date_str;
        String newfilename;
        do {
            Date date = new Date();
            date_str = (new SimpleDateFormat("yyyyMMdd")).format(date);
            long time = date.getTime();
            int random = java.lang.Math.abs((new Random()).nextInt() % 1000);
            String var3 = null;
            try {
                var3 = MessageDigest.getInstance("MD5").digest(String.valueOf(random).getBytes()).toString().replaceAll("[^a-z^A-Z^0-9]", "");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }

            date_str = date_str + time + var3;
            newfilename = filename + File.separator + date_str;
        } while ((new File(newfilename)).exists());

        return date_str;
    }

    public void valueBound(HttpSessionBindingEvent var1) {

    }

    public void valueUnbound(HttpSessionBindingEvent var1) {
        try {
            this.deleteFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}