package com.yutou.bilibili.Tools;

import com.yutou.bilibili.interfaces.DownloadInterface;
import com.yutou.common.utils.Log;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;

public class Tools {


    /**
     * 获取项目路径
     *
     * @param request
     * @return
     */
    public static String getPath(HttpServletRequest request) {
        return request.getServletContext().getRealPath("/") + "/";
    }

    /**
     * 获取客户端IP
     *
     * @param request
     * @return
     */
    public static String getRemoteAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.isEmpty() || ip.equalsIgnoreCase("unknown")) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || ip.equalsIgnoreCase("unknown")) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || ip.equalsIgnoreCase("unknown")) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * N以内的不重复随机数
     *
     * @param min 最小值
     * @param max 最大值
     * @param n
     * @return
     */
    public static int[] randomCommon(int min, int max, int n) {
        int len = max - min + 1;
        if (max < min || n > len) {
            return new int[0];
        }
        // 初始化给定范围的待选数组
        int[] source = new int[len];
        for (int i = min; i < min + len; i++) {
            source[i - min] = i;
        }
        int[] result = new int[n];
        Random rd = new Random();
        int index = 0;
        for (int i = 0; i < result.length; i++) {
            // 待选数组0到(len-2)随机一个下标
            index = Math.abs(rd.nextInt() % len--);
            // 将随机到的数放入结果集
            result[i] = source[index];
            // 将待选数组中被随机到的数，用待选数组(len-1)下标对应的数替换
            source[index] = source[len];
        }
        return result;
    }

    public static void download(String url, DownloadInterface downloadInterface) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36");
            connection.disconnect();
            new File("tmp").mkdirs();
            File file = new File("tmp" + File.separator + url.trim().split("/")[url.trim().split("/").length - 1]);
            if (file.exists()) {
                file.delete();
            }
            FileOutputStream outputStream = new FileOutputStream(file);
            InputStream inputStream = connection.getInputStream();
            byte[] bytes = new byte[4096];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            outputStream.close();
            inputStream.close();
            downloadInterface.onDownload(file);
        } catch (IOException e) {
            Log.e(e);
            downloadInterface.onError(e);
        }
    }

    /**
     * 构造给前端的文件
     *
     * @param file 文件路径
     * @return 前端获取的文件
     */
    public static ResponseEntity<FileSystemResource> getFile(File file) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        try {
            headers.add("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            headers.add("Content-Disposition", "attachment; filename=" + file.getName());
        }
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));
        return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(file));
    }

    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            Log.e(e);
            return null;
        }
        return bytesToHexString(digest.digest());
    }

    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (byte aSrc : src) {
            int v = aSrc & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static String base64ToString(String base) {
        base = base.replace(" ", "+");
        try {
            base = new String(Base64.getDecoder().decode(base.replace("\r\n", "").getBytes()));
        } catch (Exception e) {
            try {
                base = URLDecoder.decode(base, "UTF-8");
                base = base.replace(" ", "+");
                base = new String(Base64.getDecoder().decode(base.replace("\r\n", "").getBytes()));
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        return base;
    }

    /**
     * 异常输出
     *
     * @param e 异常
     * @return
     */
    public static String getExceptionString(Exception e) {
        StringWriter writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        e.printStackTrace(printWriter);
        printWriter.close();
        return writer.toString();
    }

    public static String getToDayTime() {
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    }

    //扫描文件夹
    public static List<File> scanFile(File file){
        List<File> list = new ArrayList<>();
        FileVisitor<Path> visitor = new SimpleFileVisitor<>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if ("live.db".equals(file.toFile().getName())) {
                    list.add(file.toFile());
                }
                return super.visitFile(file, attrs);
            }
        };
        try {
            Files.walkFileTree(Paths.get(file.getAbsolutePath()), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, visitor);
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
