package com.ruoyi.web.controller.image.segment;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/preprocess")
public class PreprocessController {

    private JSONObject processValue = new JSONObject();

    /**
     * 删除无效TIFF
     */
    @ApiOperation(value = "删除无效TIFF", notes = "删除无效TIFF")
    @PostMapping(value = "/deleteTiff")
    public AjaxResult deleteTiff(String basePath) throws IOException {
        List<File> nameList = deleteNodataTiff(basePath);
        return AjaxResult.success(nameList);
    }

    /**
     * 获取session中的进度值
     */
    @ApiOperation(value = "获取进度", notes = "获取进度")
    @GetMapping(value = "/getProcess")
    public AjaxResult getProcess() {
        return AjaxResult.success(processValue);
    }

    public List<File> deleteNodataTiff(String basePath) throws IOException {
        File dir = new File(basePath);
        String basePathString = basePath.split("/")[basePath.split("/").length - 1];
        Path path = Paths.get(basePath + "/" + basePathString + "list.txt");
        byte[] data = Files.readAllBytes(path);
        String result = new String(data, "utf-8");
        List<String> resultList = Arrays.asList(result.split(" "));
        List<File> fileList = new ArrayList<>(Arrays.asList(dir.listFiles()));
        int total = fileList.size();
        for (int f = 0; f < fileList.size(); f++) {
            File file = fileList.get(f);
            processValue.put("percentage", f + "/" + total);
            processValue.put("remain", total - f);
            if (file.getName().endsWith("tif")) {
                if (resultList.contains(file.getName().split("\\.")[0])) {
                    fileList.remove(f);
                    fileList.remove(f - 1);
                    fileList.remove(f - 2);
                    if (f > 2)
                        f = f - 3;
                }
            }
        }
        for (File file : fileList) {
            file.delete();
        }
        return fileList;
    }

}
