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

import io.minio.errors.*;
import io.renren.common.utils.MinIoUtils;
import io.renren.common.utils.R;
import io.renren.modules.dataSet.enumeration.DataSetType;
import org.springframework.web.bind.annotation.*;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;


@RestController
@RequestMapping("/minio")
public class MinioController {

    /**
     * Description 获取minio中指定代码文件的内容
     *
     * @return
     */
    @GetMapping("/readUrlContent")
    public String readUrlContent(String algorithmNameToVersion, String verisionToFile, long algFrameId, String fileName) throws Exception {


        //String requestUrl = minioClient.getPresignedObjectUrl(Method.GET, bucket, fileName, 1000, null);
        //使用minio工具类获取指定文件url
        if (algFrameId == -1) {
            return MinIoUtils.getFileContent("algorithm", fileName);
        }

        String requestUrl = MinIoUtils.getFileUrl("algorithm", "alg" + algorithmNameToVersion + "/version" + verisionToFile + "/" + fileName);
        HttpURLConnection conn = null;
        BufferedReader br = null;
        StringBuffer sbf = new StringBuffer();
        String content = null;
        try {
            URL url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();

            //设置不使用缓存
            conn.setUseCaches(false);

            //设置链接超时时间,毫秒为单位
            conn.setConnectTimeout(1000);

            //设置读取超时时间，毫秒为单位
            conn.setReadTimeout(1000);

            //设置当前链接是否自动处理重定向。setFollowRedirects设置所有的链接是否自动处理重定向
            conn.setInstanceFollowRedirects(false);
            //开启链接
            conn.connect();

            br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String strContent = null;
            while ((strContent = br.readLine()) != null) {
                sbf.append("\n");
                sbf.append(strContent);
            }
            sbf.delete(0, 1);
            content = sbf.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } finally {
            if (null != br) br.close();
            if (null != conn) conn.disconnect();
        }

        return content;
    }

    /**
     * Description 获取minio中指定传统算法代码文件的内容
     *
     * @return
     */
    @GetMapping("/readTraUrlContent")
    public String readTraUrlContent(String algorithmNameToVersion, String fileName) throws Exception {


        //String requestUrl = minioClient.getPresignedObjectUrl(Method.GET, bucket, fileName, 1000, null);
        //使用minio工具类获取指定文件url
        String requestUrl = MinIoUtils.getFileUrl("algorithm", "alg" + algorithmNameToVersion + "/" + fileName);
        HttpURLConnection conn = null;
        BufferedReader br = null;
        StringBuffer sbf = new StringBuffer();
        String content = null;
        try {
            URL url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();

            //设置不使用缓存
            conn.setUseCaches(false);

            //设置链接超时时间,毫秒为单位
            conn.setConnectTimeout(1000);

            //设置读取超时时间，毫秒为单位
            conn.setReadTimeout(1000);

            //设置当前链接是否自动处理重定向。setFollowRedirects设置所有的链接是否自动处理重定向
            conn.setInstanceFollowRedirects(false);
            //开启链接
            conn.connect();

            br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String strContent = null;
            while ((strContent = br.readLine()) != null) {
                sbf.append("\n");
                sbf.append(strContent);
            }
            sbf.delete(0, 1);
            content = sbf.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } finally {
            if (null != br) br.close();
            if (null != conn) conn.disconnect();
        }

        return content;
    }

    /**
     * Description 将codemirror中的内容写入文件
     *
     * @return
     * @throws IOException
     */
    @PostMapping("/writeFile")
    public R writeFile(@RequestBody HashMap<String, String> map) {
        try {
            String algorithmNameToVersion = map.get("algorithmNameToVersion");
            String verisionToFile = map.get("verisionToFile");
            String fileName = map.get("fileName");
            byte[] contentBytes = map.get("content").getBytes(); // 将字符串内容转换为字节数组
            // 构造InputStream对象
            InputStream inputStream = new ByteArrayInputStream(contentBytes);
            // 获取字节数组长度作为文件大小
            long fileSize = contentBytes.length;
            MinIoUtils.uploadFileByInputStream(inputStream, fileSize, DataSetType.ALG_DATASET.getBucketName(), "alg" + algorithmNameToVersion + "/version" + verisionToFile + "/" + fileName);
            return R.ok();
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 将codemirror中的内容写入传统算法文件
     *
     * @param map
     * @return
     */
    @PostMapping("/writeTraFile")
    public R writeTraFile(@RequestBody HashMap<String, String> map) {
        try {
            String algorithmNameToVersion = map.get("algorithmNameToVersion");
            String fileName = map.get("fileName");
            byte[] contentBytes = map.get("content").getBytes(); // 将字符串内容转换为字节数组
            // 构造InputStream对象
            InputStream inputStream = new ByteArrayInputStream(contentBytes);
            MinIoUtils.uploadFileByInputStream(inputStream, (long) contentBytes.length, DataSetType.ALG_DATASET.getBucketName(), "alg" + algorithmNameToVersion + "/" + fileName);
            return R.ok();
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 根据传入的algId与versionId以及fileName 删除文件
     *
     * @param
     * @return
     */
    @GetMapping("/deleteFile")
    public R deleteFile(String algorithmNameToVersion, String versionToFile, String fileName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
        MinIoUtils.deleteFile("algorithm", "alg" + algorithmNameToVersion + "/version" + versionToFile + "/" + fileName);
        return R.ok();
    }
}
