import numpy as np
import os
from glob import glob
from pathlib import Path
from multiprocessing import Pool
########################################################
# 函数区
########################################################

spacetySliceEnvPathExEPath=r"D:\ProgramData\miniconda3\envs\spacetySliceEnv\python.exe"

def find_tif_files_pathlib(directory):
    """
    使用pathlib.Path.rglob递归查找指定目录下所有.tif和.tiff文件

    参数:
        directory (str): 要搜索的根目录路径

    返回:
        list: 包含所有找到的.tif/.tiff文件完整路径的列表
    """
    path = Path(directory)
    # 使用rglob递归匹配所有.tif和.tiff文件
    tif_files = list(path.rglob('*.bin'))
    # 将Path对象转换为字符串路径
    return [str(file) for file in tif_files]


def find_txt_files_pathlib(directory):
    """
    使用pathlib.Path.rglob递归查找指定目录下所有.tif和.tiff文件

    参数:
        directory (str): 要搜索的根目录路径

    返回:
        list: 包含所有找到的.tif/.tiff文件完整路径的列表
    """
    path = Path(directory)
    # 使用rglob递归匹配所有.tif和.tiff文件
    tif_files = list(path.rglob('*.txt'))
    # 将Path对象转换为字符串路径
    return [str(file) for file in tif_files]


def matchTiff_Txt(tiffpaths,txtPaths):
    match_results={}
    tiffID=0
    for tid in range(len(tiffpaths)):
        tiffID=tiffID+1
        match_results[tiffID]={"tiff":tiffpaths[tid],"txt":[]}
        rootname=Path(tiffpaths[tid]).stem
        for txtpath in txtPaths:
            txtrootname=Path(txtpath).stem
            if txtrootname.startswith(rootname):
                match_results[tiffID]["txt"].append(txtpath)

    return match_results

def sliceTiFFAndTxt(match_meta,outfolderpath):
    resultTxt=""
    programpath = r"R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\DataSampleSliceTrainDataset.py"
    tiffPath=match_meta["tiff"]
    for txtpath in match_meta["txt"]:
        cmdtxt = r"{} {} -i {} -l {} -o {}".format(spacetySliceEnvPathExEPath, programpath,
                                                    tiffPath,
                                                    txtpath,
                                                    outfolderpath
                                                    )

        if os.system(cmdtxt) == 2:
            resultTxt="{}\nsucess: {}".format(resultTxt,txtpath)
            print("sucess:", cmdtxt)

        else:
            resultTxt = "{}\nfailed: {}".format(resultTxt, txtpath)
            print("failed:", cmdtxt)



if __name__ == '__main__':
    async_results = []
    with Pool() as pool:
        # 聚束模式
        preFolderPath = r"D:\Annotation_Y\预处理\聚束模式"
        outfolderPath=r"D:\Annotation_Y\切片样本\聚束模式"
        tiffPaths = find_tif_files_pathlib(preFolderPath)
        txtPaths = find_txt_files_pathlib(preFolderPath)
        match_results=matchTiff_Txt(tiffPaths,txtPaths)

        for tiffID in match_results:
            match_meta=match_results[tiffID]
            async_results.append(
                pool.apply_async(sliceTiFFAndTxt, (match_meta,outfolderPath,))
            )

        # 聚束模式
        preFolderPath = r"D:\Annotation_Y\预处理\条带模式"
        outfolderPath=r"D:\Annotation_Y\切片样本\条带模式"
        tiffPaths = find_tif_files_pathlib(preFolderPath)
        txtPaths = find_txt_files_pathlib(preFolderPath)
        match_results=matchTiff_Txt(tiffPaths,txtPaths)

        for tiffID in match_results:
            match_meta=match_results[tiffID]
            async_results.append(
                pool.apply_async(sliceTiFFAndTxt, (match_meta,outfolderPath,))
            )

        for async_result in async_results:
            print(async_result.get())

