package io.renren.modules.sys.controller.dataPreProcess;

import io.minio.errors.*;
import io.renren.common.utils.MinIoUtils;
import io.renren.common.utils.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@RestController
@RequestMapping("/dataPreProcess")
public class DataPreProcessController {
    @Value("${datasetLocation}")
    String datasetLocation;

    @Value("${dataPreProcessLocation}")
    String dataPreProcessLocation;

    @GetMapping("/dataPreProcessByPython")
    public R testDownloadMinioFile(String datasetName,String preProcessMethod,String featureMark) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
        //先判断该文件是否存在，若存在则删除
        String fileName=datasetLocation+"/"+datasetName;
        File file=new File(fileName);
        if(file.exists()){
            file.delete();
        }

        //先将数据集从minio里下载到本地
        MinIoUtils.downloadFile("dataset",datasetName,datasetLocation+"/"+datasetName);

        //调用python 处理数据集
        String[] arguments= new String[]{"python", dataPreProcessLocation + "/dataPreHandle.py", datasetLocation + "/" + datasetName, preProcessMethod,featureMark};

        try {
            Process process=Runtime.getRuntime().exec(arguments);
            BufferedReader in=new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));
            String line=null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            //java代码中的process.waitFor()返回值为0表示我们调用python脚本成功，
            //返回值为1表示调用python脚本失败，这和我们通常意义上见到的0与1定义正好相反
            int re = process.waitFor();
            System.out.println(re);
        }catch (Exception e){
            e.printStackTrace();
        }

        return R.ok();
    }
}
