package com.example.demo.utils;
import java.nio.file.Files;
import java.nio.charset.StandardCharsets;
import com.example.demo.model.DealProcessSream;
import com.example.demo.model.StrAndEmail;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Arrays;

@Slf4j
public class DoPerlUtil {


    /**
     * 以文件作为脚本输入产生结果文件的方法
     *
     * @param strAndEmail 用户提交的输入文件
     * @return 脚本执行后返回输出文件的绝对路径
     */
    public static String doPerFile(StrAndEmail strAndEmail) {


//        perl
// /howe/xiangyang/noxLu/Typestrain_ANLI/bash_fastANL. pl
// -u /hone /xsiangyang/noxiu/upload_dr
// -t /hone /xAtangyang/noxtu/lyrestratn ANY/Typestrain_sEQ
// -s 2 -N 16 -e 397316815@qq.com

//        perl文件的绝对路径
        String perlPath = "/home/ubuntu/Bio-server/TypeStrain_ANI/bash_fastANI.pl";
        String arg1 = "-u";
        String arg2 = "-s";
        String arg3 = "-m";
        String arg4 = "-e";
        String arg5 = "-t";
        String arg6 = "-b";

        String resultPath = "";

        if (strAndEmail.getThreadNum() == 0) {
            strAndEmail.setThreadNum(20);
        }
        if (strAndEmail.getSqlNum() == 0) {
            strAndEmail.setSqlNum(30);
        }
        try {


            String[] cmd = {"perl", perlPath,
                    arg1, strAndEmail.getStr(),
                    arg2, String.valueOf(strAndEmail.getSqlNum()),
                    arg3, String.valueOf(strAndEmail.getThreadNum()),
                    arg4, strAndEmail.getEmail(),
                    arg5, strAndEmail.getDoUniprot(),
                    arg6, strAndEmail.getPgapSelopt()
            };

            log.info(Arrays.toString(cmd));

            Process process = Runtime.getRuntime().exec(cmd);


            new DealProcessSream(process.getInputStream()).start();
            new DealProcessSream(process.getErrorStream()).start();

//            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
//            log.info("读取脚本返回开始");
//
//
//            String line;
//            while ((line = reader.readLine()) != null) {
//                System.out.println("脚本返回的信息：" + line);
//                resultPath = line;
//            }
//
//            reader.close();
////
//
//            log.info("读取脚本返回结束");
//            process.destroy();
//            int status = process.waitFor();
//            if (status != 0) {
//                System.out.println("Command failed with code: " + status);
//            } else {
//                System.out.println("Command executed successfully");
//            }

            // 检查进程是否已经退出
            if (process.isAlive()) {
                // 进程还在运行，等待它退出
                process.waitFor();
            }
            int i = process.exitValue();
            System.out.println(i);


        } catch (IOException e) {
            return e.getMessage();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return resultPath;
    }


    public static int doPerlEmail(String n, String str, String email) {

        String perlPath = "/home/ubuntu/Bio-server/TypeStrain_ANI/sendEmail0.pl";


        String[] cmd = {"perl", perlPath
                , "-n"
                , n
                , "-w"
                , str
                , "-t", email};

        log.info(Arrays.toString(cmd));

        try {
            Process process = Runtime.getRuntime().exec(cmd);

            log.info(String.valueOf(process.waitFor()));

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));


            log.info("读取脚本返回开始");
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("Output: " + line);

            }


            log.info("读取脚本返回结束");

            reader.close();

            new DealProcessSream(process.getInputStream()).start();
            new DealProcessSream(process.getErrorStream()).start();
            process.destroy();
            int status = process.waitFor();
            if (status != 0) {
                System.out.println("Command failed with code: " + status);
                return 1;
            } else {
                System.out.println("Command executed successfully");

            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return 0;
    }


    /**
     * 20240824添加
     * 执行AfterPhylo.pl
     * 修改treeString
     */
    public static String doPerltree(String str, String n, String a) {  
        // 构建命令并执行  
        String perlPath = "/home/ubuntu/Bio-server/bin/AfterPhylo.sh";
        String[] cmd = {"bash", perlPath, "-s", str, "-c", n, "-a", a};
        log.info(Arrays.toString(cmd));
         
        ProcessBuilder pb = new ProcessBuilder(cmd);  
        Process p;  
        try {  
            p = pb.start();  
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));  
            StringBuilder output = new StringBuilder();  
            String line;  
            while ((line = reader.readLine()) != null) {  
                output.append(line).append("\n");  
            }  
            int exitCode = p.waitFor();  
            if (exitCode == 0) {  
                return output.toString().trim(); // 返回捕获的输出（去除尾随换行符）  
            } else {  
                throw new RuntimeException("Perl script failed with exit code: " + exitCode);  
            }  
        } catch (IOException | InterruptedException e) {  
            throw new RuntimeException("Error executing Perl script", e);  
        }  
    }
    
    
    /**
     * 20250111添加
     * 执行check_uploadfile_totalFileNum.pl
     * 计算上传的压缩序列文件中，含有文件总数
     */
    public static String uploadFormatPlusFileNumPerl(String str) {
        // 组装命令并执行
        String perlPath = "/home/ubuntu/Bio-server/bin/check_uploadfile_Format_plus_totalFileNum.pl";
        String[] cmd = {"perl", perlPath, str};
        log.info(Arrays.toString(cmd));

        ProcessBuilder cf = new ProcessBuilder(cmd);
        Process perlProcess;
        try {
            perlProcess = cf.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(perlProcess.getInputStream()));
            String lastLine = null; // 初始化变量以保存最后一行输出
            String line;
            while ((line = reader.readLine()) != null) {
                lastLine = line; // 更新最后一行输出的内容
            }
            int exitCode = perlProcess.waitFor();
            if (exitCode == 0) {
                // 去除可能存在的尾随换行符，并返回最后一行输出
                return lastLine == null ? "" : lastLine.trim();
            } else {
                throw new RuntimeException("Perl脚本执行失败，退出码为: " + exitCode);
            }
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException("执行Perl脚本时出错", e);
        }
    }
    
    
    /**
     * 20250112添加
     * 执行svg2pdf.py
     * 执行svg2figure.py后获得pdf文件
     */
    public static File doPythonSvgToPdf(String svgContent) throws IOException {
        // 创建临时文件
        File tempSvgFile = null;
        File tempPdfFile = null;
        
        // 生成一个唯一的临时SVG文件名，避免冲突
        String tempSvgFileName = "/home/ubuntu/Bio-server/bin/tmp/" + "temp_svg_" + System.currentTimeMillis() + ".svg";
        tempSvgFile = new File(tempSvgFileName);
        String tempPdfFileName = "/home/ubuntu/Bio-server/bin/tmp/" + "temp_pdf_" + System.currentTimeMillis() + ".pdf";
        tempPdfFile = new File(tempPdfFileName);
        Files.write(tempSvgFile.toPath(), svgContent.getBytes(StandardCharsets.UTF_8));

        // 指定输出PDF文件的路径（固定路径）
        String pythonPath = "/home/ubuntu/Bio-server/bin/svg2pdf.py";
        String[] cmd = {"python", pythonPath, tempSvgFile.getAbsolutePath(), tempPdfFile.getAbsolutePath()};
        log.info(Arrays.toString(cmd));
            
        ProcessBuilder psp = new ProcessBuilder(cmd);
        Process pythonProcess; 

        // 读取并打印错误输出
        try {
            pythonProcess = psp.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(pythonProcess.getErrorStream()));
            String errorLine;
            while ((errorLine = reader.readLine()) != null) {
                System.err.println(errorLine);
            }
            int exitCode = pythonProcess.waitFor();
            if (exitCode == 0) {
                return new File(tempPdfFile.getAbsolutePath()); // 返回PDF文件的路径
            } else {
                throw new RuntimeException("Python script execution failed with exit code: " + exitCode);
            }
        }catch (IOException e) {
            // 处理异常，例如打印堆栈跟踪或记录日志
            e.printStackTrace();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 确保临时SVG文件被删除
            if (tempSvgFile != null && tempSvgFile.exists()) {
                tempSvgFile.delete();
            }
        }
        return new File(tempPdfFile.getAbsolutePath()); // 返回PDF文件的路径
    }
    
    
    /**
     * 删除文件
     *
     * @param filePath
     */
    public static void deleteUploadFileByPath(String filePath) {


        String[] cmd = {"sudo", "rm", "-rf", filePath};

        try {
            Process process = Runtime.getRuntime().exec(cmd);
            try {
                int i = process.waitFor();
                System.out.println("删除文件的执行结果：" + i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
