package net.northking.cctp.scriptcase.tools;

import com.alibaba.fastjson.JSON;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.util.UUIDUtil;
import net.northking.cctp.scriptcase.enums.ErrorMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.*;

@Component
public class MinioPathUtils {
    private static final Logger logger = LoggerFactory.getLogger(MinioPathUtils.class);

    private static final String TEMP_FILE_PATH = MinioPathUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();

    public static String pathToId(String tenantId,String path){
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }
        String str = path.replaceAll("/", "_");
        return tenantId + str;
    }

    /**
          * 第一个是租户id,第二个是文件id，第三个是文件名
          * @param fileId
          * @return
          */
    public static String[] idToPath(String fileId) {
        String[] result = new String[3];
        if (fileId.startsWith("/") || fileId.startsWith("_")) {
            fileId = fileId.substring(1);
        }
        if (fileId.endsWith("/") || fileId.endsWith("_")) {
            fileId = fileId.substring(0, fileId.length() - 1);
        }
        int index = fileId.indexOf("_");
        result[0] = fileId.substring(0, index);  //租户id
        result[1] = fileId.substring(index + 1);  //文件id
        result[2] = result[1];  //文件名
        return result;
    }

    public static<T> File objectToJsonFile(T t) {
        String objectStr = JSON.toJSONString(t);
        byte[] bytes = new byte[0];
        try {
            bytes = objectStr.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("",e);
            logger.info("数据转换二进制失败");
        }
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);  //获取脚本输入流
        File tempFilePath = new File(TEMP_FILE_PATH);
        if (!tempFilePath.exists()) {
            tempFilePath.mkdirs();
        }
        File file = new File(TEMP_FILE_PATH + "/tempFile" + UUIDUtil.create32UUID() + ".json");
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
            byte[] readBytes = new byte[1024 * 1024];
            int length = 0;
            while ((length = inputStream.read(readBytes, 0, readBytes.length)) > 0) {
                fileOutputStream.write(readBytes,0,length);
            }
            fileOutputStream.flush();
        } catch (Exception e) {
            logger.error("object写入文件出错");
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                logger.error("",e);
            }
            if (null != fileOutputStream) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    logger.error("",e);
                }
            }

        }
        return file;
    }

    public static<T> T getFileContent(InputStream inputStream, Class<T> clazz) {
        InputStreamReader streamReader = null;
        BufferedReader reader = null;
        T t = null;
        try {
            streamReader = new InputStreamReader(inputStream,"UTF-8");
            reader = new BufferedReader(streamReader);
            StringBuilder builder = new StringBuilder();
            String temp = "";
            while (null != (temp = reader.readLine())) {
                builder.append(temp);
            }
            String jsonStr = builder.toString();
            if (StringUtils.hasText(jsonStr)) {
                t = JSON.parseObject(JSON.parse(jsonStr).toString(), clazz);
            }
        } catch (IOException e) {
            logger.error("读取文件内容失败");
            throw new PlatformRuntimeException(new ErrorMessage("读取文件内容失败"));
        }finally {
            if (null != streamReader) {
                try {
                    streamReader.close();
                } catch (IOException e) {
                    logger.error("",e);
                }
            }
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("",e);
                }
            }
        }
        return t;
    }

}
