import SimpleITK as sitk
from pydicom import dicomio
import os
import numpy as np
import glob
from tqdm import tqdm

def control_single(target_path):

    dcms = os.listdir(target_path)

    if len(dcms) < 30:
        return 'LAYERCOUNT_LESS'

    # dcm_names = [int(name.split('.')[0], 16) for name in dcms]
    # #print(len(dcm_names), len(set(dcm_names)))
    # if len(dcm_names) != len(set(dcm_names)):
    #     return 'NO INSTANCE_NUM_BREAK'   

    # sorted_names = sorted(dcm_names)
    #print(sorted_names)
    #for i in range(len(sorted_names) - 1):
    #    if sorted_names[i + 1] != sorted_names[i] + 1:
    #        return 'NO INSTANCE_NUM_BREAK'  

    dcm = dicomio.read_file(os.path.join(target_path, dcms[0]), force=True)
    if dcm.get('Modality', '') not in ['CT', 'CTSR', 'SRCT']:
        return 'NOT_CT'
    
    #check_strs = ['chest', 'thorax', 'lung', 'thorroutine', '胸', '肺', '肋']
    check_strs = ['chest', 'thorax', 'lung', 'nodule']
    #check_res = False
    check_results = np.zeros(4)
    for i, target_str in enumerate([dcm.get('StudyDescription', ''), dcm.get('SeriesDescription', ''),
                                    dcm.get('BodyPartExamined', ''), dcm.get('ProtocolName', '')]):
        #target_str = target_str.lower()
        #print(f'target str:---{target_str}---')
        #for j in check_strs:
        #    if j in target_str:
        #        check_res = True
        #        break
        #if check_res:
        #    break
        #print(target_str)
        score = np.zeros(len(check_strs))
        for idx, cstr in enumerate(check_strs):
            if target_str.lower().find(cstr) != -1:
                score[idx] = 1
        if list(score).count(1) != 0:
            check_results[i] = 1
    if sum(check_results) == 0:
        return 'MISS_SPECFIC_STR'
    #if not check_res:
    #    return 'MISS_SPECFIC_STR'
    if dcm.get('SliceThickness', '') <= 0:
        return 'MISS_SLICETHICKNESS'

    if (dcm.get('Rows', '') == dcm.get('Columns', '')) and (dcm.get('Rows', '') == 512 or dcm.get('Columns', '') == 1024):
        pass
    else:
        return 'ROW_COLUMS' 
    
    for idx, value in enumerate(list(dcm.get('ImageOrientationPatient', ''))):
        if int(value) != int(float(['1.0', '0.0', '0.0', '0.0', '1.0', '0.0'][idx])):
            return 'IMAGEORIENTATIONPATIENT_CAUSE'
    
    return 'SUCCESS'