package com.yizhi.application.assignment.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.yizhi.core.application.exception.FileReadException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


@Component("fileReadUtil1")
public class FileReadUtil {

    private static final Logger LOG = LoggerFactory.getLogger(FileReadUtil.class);

    public File read(String urlStr, String savePath, String fileName) {

        File fileInfo = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] buffer = new byte[1024];
            int len = 0;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.close();

            byte[] getData = bos.toByteArray();
            //文件保存位置
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }


            String fileName1 = saveDir + File.separator + fileName;
            LOG.info("####################fileName:" + fileName1);
            fileInfo = new File(new String(fileName1.getBytes("UTF-8")));
            LOG.info("####################fileName,绝对路径:" + fileInfo.getAbsolutePath());
            LOG.info("####################语言格式" + System.getProperty("sun.jnu.encoding"));
            FileOutputStream fos = new FileOutputStream(fileInfo);
            fos.write(getData);
            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (Exception e) {
            LOG.error("文件拉取失败", e);
            throw new FileReadException();
        }
        return fileInfo;
    }

    /**
     * 把特殊字符全替换成下划线
     *
     * @param character
     * @return
     */
    public String getSpecialCharacter(String character) {
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(character);
        return m.replaceAll("_").trim();
    }
}
