package com.example.sjkbf.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.log.StaticLog;
import com.example.sjkbf.common.FileManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import cn.hutool.core.io.file.FileReader;

import org.springframework.http.ResponseEntity;


import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * InnoDB free: 11264 kB 前端控制器
 * </p>
 *
 * @author bozhiqiang
 * @since 2022-04-03
 */
@RestController
@RequestMapping("/dps")
public class AccountCargoController {

    @Autowired
    FileManage fileManage;

    public static Map<String,Integer> a=new HashMap<>();

    @RequestMapping("/login")
    public int login(HttpServletRequest request) {

        String ipAddress = getIpAddress(request);
        a.put(ipAddress,a.size()+1);
        return a.size();
    }

    @RequestMapping("/getversion")
    public String getversion() {

        FileReader fileReader = new FileReader(fileManage.getDpsfile()+"Application/Proj.ifo");
        String result = fileReader.readString();
        return result;
    }


    @RequestMapping("/getclientversion")
    public String getclientversion() {

        FileReader fileReader = new FileReader(fileManage.getDpsfile()+"Marketplace/Proj.ifo");
        String result = fileReader.readString();

        return result;
    }

    @RequestMapping("/getlist")
    public String getlist() {


        File[] ls = FileUtil.ls(fileManage.getDpsfile()+"Script");

        StringBuilder list = new StringBuilder("{ \"list\":[");
        for (File l : ls) {
            FileReader fileReader = new FileReader(l+"/"+"Proj.ifo");

            list.append(fileReader.readString()).append(",");
        }
        list.deleteCharAt(list.length() - 1);
        list.append("]}");
        return list.toString();
    }

    @RequestMapping("/getadvertisement")
    public String getadvertisement() {


        File[] ls = FileUtil.ls(fileManage.getDpsfile()+"Advertisement");
        //按文件夹名字排序
        Arrays.sort(ls, Comparator.comparing(File::getName));
        StringBuilder list = new StringBuilder("{ \"list\":[");
        for (File l : ls) {
            FileReader fileReader = new FileReader(l+"/"+"info.ifo");

            list.append(fileReader.readString()).append(",");
        }
        list.deleteCharAt(list.length() - 1);
        list.append("]}");
        return list.toString();
    }

    // 使用正则表达式捕获所有字符（包括斜杠）
    @PostMapping("/download/{colonPath}")
    public ResponseEntity<Resource> download(
            @PathVariable String colonPath) throws Exception {

        // 1. 解码中文路径
        String decodedPath = URLDecoder.decode(colonPath, "UTF-8");
//        System.out.println("接收到参数: " + decodedPath);

        // 2. 将冒号还原为斜杠
        String realPath = decodedPath.replace(":", "/");
//        System.out.println("真实路径: " + realPath);
        StaticLog.info( "文件下载1: " + realPath );
        // 3. 构建绝对路径
        Path baseDir = Paths.get(fileManage.getDpsfile()+"Script").toAbsolutePath().normalize();
        Path targetPath = baseDir.resolve(realPath).normalize();

        // 4. 安全校验（防止路径穿越）
        if (!targetPath.startsWith(baseDir)) {
            System.err.println("非法路径尝试: " + realPath);
            return ResponseEntity.status(403).build();
        }

        // 5. 返回文件
        Resource resource = new FileSystemResource(targetPath);
        if (!resource.exists()) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok()
                .header("Content-Disposition",
                        "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }


    // 使用正则表达式捕获所有字符（包括斜杠）
    @PostMapping ("/download2/{colonPath}")
    public ResponseEntity<Resource> download2(
            @PathVariable String colonPath) throws Exception {

        // 1. 解码中文路径
        String decodedPath = URLDecoder.decode(colonPath, "UTF-8");
//        System.out.println("接收到参数: " + decodedPath);

        // 2. 将冒号还原为斜杠
        String realPath = decodedPath.replace(":", "/");
//        System.out.println("真实路径: " + realPath);
        // 3. 构建绝对路径
        Path baseDir = Paths.get(fileManage.getDpsfile()+"Application").toAbsolutePath().normalize();
        Path targetPath = baseDir.resolve(realPath).normalize();

        // 4. 安全校验（防止路径穿越）
        if (!targetPath.startsWith(baseDir)) {
            System.err.println("非法路径尝试: " + realPath);
            return ResponseEntity.status(403).build();
        }

        // 5. 返回文件
        Resource resource = new FileSystemResource(targetPath);
        if (!resource.exists()) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok()
                .header("Content-Disposition",
                        "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }

    @RequestMapping("/download3/{colonPath}")
    public ResponseEntity<Resource> download3(
            @PathVariable String colonPath) throws Exception {

        // 1. 解码中文路径
        String decodedPath = URLDecoder.decode(colonPath, "UTF-8");
//        System.out.println("接收到参数: " + decodedPath);

        // 2. 将冒号还原为斜杠
        String realPath = decodedPath.replace(":", "/");
//        System.out.println("真实路径: " + realPath);

        // 3. 构建绝对路径
        Path baseDir = Paths.get(fileManage.getDpsfile()+"Advertisement").toAbsolutePath().normalize();
        Path targetPath = baseDir.resolve(realPath).normalize();

        // 4. 安全校验（防止路径穿越）
        if (!targetPath.startsWith(baseDir)) {
            System.err.println("非法路径尝试: " + realPath);
            return ResponseEntity.status(403).build();
        }

        // 5. 返回文件
        Resource resource = new FileSystemResource(targetPath);
        if (!resource.exists()) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok()
                .header("Content-Disposition",
                        "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }

    public static void main(String[] args) {

        File[] ls = FileUtil.ls("C:\\Users\\12134\\Downloads\\Advertisement");

        StringBuilder list = new StringBuilder("{ \"list\":[");
        for (File l : ls) {
            FileReader fileReader = new FileReader(l+"\\"+"info.ifo");

            list.append(fileReader.readString()).append(",");
        }
        list.deleteCharAt(list.length() - 1);
        list.append("]}");

        System.out.println(list.toString());
    }

    //添加
    public static String processCommand(String input) {
        // 按行处理以保留格式
        String[] lines = input.split("\n");
        StringBuilder result = new StringBuilder();

        for (String line : lines) {
            // 处理包含df_game_r的命令行（包括注释行）
            if (line.contains("./df_game_r siroco")) {
                line = processGameLine(line);
            }

            result.append(line).append("\n");
        }

        return result.toString().trim();
    }

    private static String processGameLine(String line) {
        // 检查是否是注释行
        boolean isCommented = line.trim().startsWith("#");
        String workingLine = isCommented ? line.substring(line.indexOf("#") + 1) : line;

        // 检查是否已有LD_PRELOAD
        Matcher preloadMatcher = Pattern.compile("LD_PRELOAD\\s*=\\s*\"([^\"]*)\"").matcher(workingLine);

        if (preloadMatcher.find()) {
            // 已有LD_PRELOAD的情况：确保包含目标库
            String libs = preloadMatcher.group(1).trim();
            if (!libs.contains("/dp_s/lib/libAurora.so")) {
                String newLibs = "/dp_s/lib/libAurora.so" + (libs.isEmpty() ? "" : " " + libs);
                workingLine = workingLine.replaceFirst("LD_PRELOAD\\s*=\\s*\"[^\"]*\"",
                        "LD_PRELOAD=\" " + newLibs + "\"");
            }
        } else {
            // 没有LD_PRELOAD的情况：添加
            workingLine = workingLine.replaceFirst("(\\./df_game_r\\s+siroco)",
                    "LD_PRELOAD=\" /dp_s/lib/libAurora.so\" $1");
        }

        return isCommented ? "#" + workingLine : workingLine;
    }

    //删除
    public static String cleanLdPreload(String input) {
        // 使用Matcher的region功能保留所有换行符
        StringBuilder result = new StringBuilder();
        Pattern pattern = Pattern.compile(
                "(LD_PRELOAD\\s*=\\s*\")([^\"]*?)/dp_s/lib/libAurora\\.so([^\"]*?)(\")|" +
                        "(LD_PRELOAD\\s*=\\s*\"\\s*\")"
        );

        Matcher matcher = pattern.matcher(input);
        int lastPos = 0;

        while (matcher.find()) {
            // 添加匹配前的内容（包含所有换行符）
            result.append(input, lastPos, matcher.start());

            // 处理匹配到的内容
            if (matcher.group(1) != null) {  // 情况1：包含Aurora.so
                String replacement = matcher.group(1) +
                        matcher.group(2) +
                        matcher.group(3) +
                        matcher.group(4);
                // 如果替换后变成LD_PRELOAD=""，则完全删除
                if (replacement.equals("LD_PRELOAD=\"\"")) {
                    // 不添加任何内容（相当于删除）
                } else {
                    result.append(replacement);
                }
            } else {  // 情况2：空的LD_PRELOAD
                // 完全跳过不添加（删除）
            }

            lastPos = matcher.end();
        }

        // 添加剩余内容
        result.append(input.substring(lastPos));

        return result.toString();
    }

    public static String getIpAddress(HttpServletRequest request) {
        // 获取请求的IP地址
        String ipAddress = request.getRemoteAddr();
        // 如果应用部署在反向代理或负载均衡器后面，可以通过X-Forwarded-For头部获取真实IP地址
        String forwardedFor = request.getHeader("X-Forwarded-For");
        if (forwardedFor != null && !forwardedFor.isEmpty()) {
            ipAddress = forwardedFor.split(",")[0];
        }
        return ipAddress;
    }




}
