package com.testor.common.helper;

import com.testor.biz.file.FileTypeEnum;
import com.tongtech.tfw.backend.core.constants.StringConstants;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.io.FileHelper;
import lombok.extern.slf4j.Slf4j;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * CommonHelper
 *
 * <p>//TODO
 *
 * @author ivan
 * @version 1.0 Created by ivan at 12/24/20.
 */
@Slf4j
public class CommonHelper {
  /*
   * File Download
   * @author Created by ivan on 1:54 PM 12/24/20.
   * @param fileName : File name
   * @param filePath : File Path
   * @param res : Response
   * @return void
   **/
  public static void fileDownload(String fileName, String filePath, HttpServletResponse response)
          throws UnsupportedEncodingException {
    String type = new MimetypesFileTypeMap().getContentType(fileName);
    String encodeFileName = URLEncoder.encode(fileName, StringConstants.UTF_8);
    encodeFileName = StringHelper.replace(encodeFileName, "+", "%20");
    response.setHeader("Content-type", type);
    response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
    //        "attachment;filename*=utf-8''" + encodeFileName);
    response.setHeader("Content-Disposition", "attachment;filename=" + encodeFileName);
    // 发送给客户端的数据
    OutputStream outputStream = null;
    BufferedInputStream bis = null;
    try {
      outputStream = response.getOutputStream();
      byte[] buff = new byte[1024];
      // filepath
      File localFile = FileHelper.file(filePath);
      response.setContentLength((int) localFile.length());
      bis = new BufferedInputStream(new FileInputStream(localFile));
      int i = bis.read(buff);
      while (i != -1) {
        outputStream.write(buff, 0, i);
        outputStream.flush();
        i = bis.read(buff);
      }
    } catch (IOException e) {
      log.error("文件下载失败！文件为{}", fileName, e);
    } finally {
      try {
        if (null != outputStream) {
          outputStream.close();
        }
        if (null != bis) {
          bis.close();
        }
      } catch (IOException e) {
        log.error("close io error....", e);
      }
    }
  }

  public static boolean checkFileType(byte[] fileContent, String ext) {
    for (FileTypeEnum fileTypeEnum : FileTypeEnum.values()) {
      if (ext.endsWith(fileTypeEnum.getKeyWords())) {
        Integer length = fileTypeEnum.getLength();
        String header = fileTypeEnum.getHeader();
        StringBuilder received = new StringBuilder();
        for (int i = 0; i < length / 2; i++) {
          received.append(Integer.toHexString(fileContent[i] & 0xFF));
        }
        if (!received.toString().toUpperCase().equals(header)) {
          return false;
        }
      }
    }
    return true;
  }
}
