import os
import sys
import json
import glob
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split

def bbox_iou(point1,point2):
    z,y,x,dz,dy,dx = point1
    z1,y1,x1,dz1,dy1,dx1 = point2

    z_min,z_max = z-dz/2.0,z+dz/2.0
    y_min,y_max = y-dy/2.0,y+dy/2.0
    x_min,x_max = x-dx/2.0,x+dx/2.0

    z_min_1,z_max_1 = z1-dz1/2.0,z1+dz1/2.0
    y_min_1,y_max_1 = y1-dy1/2.0,y1+dy1/2.0
    x_min_1,x_max_1 = x1-dx1/2.0,x1+dx1/2.0

    ####### calculate intersection region
    z_min_max,z_max_min = max(z_min,z_min_1),min(z_max,z_max_1)
    y_min_max,y_max_min = max(y_min,y_min_1),min(y_max,y_max_1)
    x_min_max,x_max_min = max(x_min,x_min_1),min(x_max,x_max_1)
    
    depth_inter = z_max_min - z_min_max
    height_inter = y_max_min - y_min_max
    width_inter = x_max_min - x_min_max
    iou_val = 0
    if ((depth_inter<0) or(height_inter<0) or (width_inter<0)):
        return iou_val
    
    intersection = (depth_inter*height_inter*width_inter)
    cubaA = dz*dy*dx
    cubaB = dz1*dy1*dx1
    union = cubaA+cubaB-intersection
    return intersection/float(union)
    
def split_dataset(uids,split_ratios):
    '''
    根据比例将uid进行分组，返回分组后的uid信息
    '''
    
    if len(split_ratios)==0 or split_ratios[0]==1:
        return [uids,None,None]
    else:
        train_uids,val_uids = train_test_split(uids, test_size=split_ratios[0], random_state=42)
        if len(split_ratios)==1 or split_ratios[1]==1:
            return [train_uids,val_uids,None]
        else:
            val_uids,test_uids = train_test_split(val_uids, test_size=split_ratios[1], random_state=42)
            return [train_uids,val_uids,test_uids]
    

def WriteTxt(info,path):
    with open(path,'w') as f:
        for record in info:
            f.write(record+'\n')
    f.close()

def ReadTxt(path):
    with open(path,'r') as f:
        result = f.readlines()
    f.close()
    return [x.strip() for x in result]


def ReadCSV(path):
    if 'csv' in path:
        df = pd.read_csv(path,encoding='utf_8_sig')
        return df
    elif 'xlsx' in path:
        df = pd.read_excel(path,encoding='utf_8_sig')
        return df

def LoadDFs(paths):
    result = []
    for path in paths:
        if ('csv' not in path) and ('xlsx' not in path):
            continue 
        df = ReadCSV(path)
        result.append(df)
    if len(result)>0:
        return pd.concat(result,ignore_index=True)

def ReadJson(path):
    f = open(path)
    content = f.read()
    result = json.loads(content)
    return result
