from opcode import opname

from osgeo import ogr
import os
import argparse
from osgeo import ogr, gdal
import os
import argparse
import numpy as np
from scipy.spatial import KDTree
from tools.DotaOperator import DotaObj,readDotaFile,writerDotaFile,createDota
from glob import glob
from pathlib import Path
import shutil
from tqdm import tqdm


MLCName="MLC" # M
JLCName="JLC" # J
MJLCName="MJLC" # JM 混合
NOLCName="NOLC" # 没有港口


def existOrCreate(dirpath):
    if not os.path.exists(dirpath):
        os.makedirs(dirpath)


def find_tifPort_files_pathlib(directory):
    path = Path(directory)
    # 使用rglob递归匹配所有.tif和.tiff文件
    tif_files = list(path.rglob('sumMJPort.txt'))
    # 将Path对象转换为字符串路径
    return [str(file) for file in tif_files]


def find_label_files_pathlib(directory):
    path = Path(directory)
    # 使用rglob递归匹配所有.tif和.tiff文件
    tif_files = list(path.rglob('*.txt'))
    # 将Path对象转换为字符串路径
    return [str(file) for file in tif_files]

def read_MJPortFile(sumMJPortfilepath,deepsdict=None):
    lines=None
    with open(sumMJPortfilepath,'r',encoding="utf-8") as f:
        lines= f.readlines()
    if deepsdict is None :
        deepsdict={}
    for linestr in lines:
        if len(linestr)<3:
            continue
        clsname=linestr.split("\t\t")[0]
        tiffpath=linestr.split("\t\t")[1].replace("\n","")
        rootname=Path(tiffpath).stem
        deepsdict[rootname]=clsname
    return deepsdict



def SpliteProcess(srcfolderpath,infolderpath,outfolderpath):
    sumMJPortPaths=find_tifPort_files_pathlib(srcfolderpath)
    sumMJPortDict={}
    print("读取港口归属文件")
    for sumMJPortfilepath in tqdm(sumMJPortPaths):
        sumMJPortDict=read_MJPortFile(sumMJPortfilepath,sumMJPortDict)

    labeltxtPaths=find_label_files_pathlib(infolderpath)

    JportLabel=os.path.join(outfolderpath,'军港')
    MportLabel=os.path.join(outfolderpath,'民港')
    MJportLabel=os.path.join(outfolderpath,'混合港')
    NoportLabel=os.path.join(outfolderpath,'无港口')

    existOrCreate(JportLabel)
    existOrCreate(MportLabel)
    existOrCreate(MJportLabel)
    existOrCreate(NoportLabel)

    # 软件
    for labeltxtpath in tqdm(labeltxtPaths):
        rootname=Path(labeltxtpath).stem
        tiffpath=labeltxtpath.replace(".txt",".tif")
        if not os.path.exists(tiffpath):
            tiffpath=labeltxtpath.replace(".txt",".tiff")
        if not os.path.exists(tiffpath):
            print("error not fount: ",tiffpath)
        rootname=rootname.replace("_image.txt","").replace("_image","")
        idx=rootname.rfind("_")
        rootname=rootname[:idx]
        trgpath=None

        if rootname in sumMJPortDict:
            clsname=sumMJPortDict[rootname]
            if MLCName == clsname: # M
                trgpath=MportLabel
            elif JLCName == clsname: # J
                trgpath=JportLabel
            elif MJLCName == clsname:  # JM 混合
                trgpath=MJportLabel
            elif NOLCName == clsname: # 没有港口
                trgpath=NoportLabel
                clsname="MLC"
            else:
                print("error: ", Path(labeltxtpath).stem)
                continue

            # shutil.copy(labeltxtpath, os.path.join(trgpath, os.path.basename(labeltxtpath)))
            newlabelpath=os.path.join(trgpath, os.path.basename(labeltxtpath))
            dotametas=readDotaFile(labeltxtpath)
            for dotaid in range(len(dotametas)):
                dotametas[dotaid].clsname=clsname
            writerDotaFile(dotametas,newlabelpath)
            shutil.copy(tiffpath, os.path.join(trgpath, os.path.basename(tiffpath)))
        else:
            print("error: ", Path(labeltxtpath).stem)

    return True
    pass


def getParams():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s','--srcfolder',type=str,default=r'D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口', help='输入shapefile文件')
    parser.add_argument('-i','--inlabelfolder',type=str,default=r'R:\TYSAR-德清院\D-切片成果\TYSAR-条带模式(SM)\港口\切片结果整理', help='输入shapefile文件')
    parser.add_argument('-o', '--outfolder',type=str,default=r'R:\TYSAR-德清院\D-切片成果\TYSAR-条带模式(SM)\港口\舰船')
    args = parser.parse_args()
    return args

if __name__ == '__main__':
    try:
        parser = getParams()
        srcfolder=parser.srcfolder
        infolder=parser.inlabelfolder
        outfolder=parser.outfolder
        print('srcfolder=',srcfolder)
        print('infolder=',infolder)
        print('outfolder=',outfolder)
        SpliteProcess(srcfolder,infolder,outfolder)
        exit(2)
    except Exception as e:
        print(e)
        exit(3)
