import copy
from tqdm import tqdm
from pathlib import Path
from dataTools import limitLenStr

def get_transparent(img,threshold=0.7):
    import cv2
    import numpy as np
    img=copy.deepcopy(img)
    if img.shape[-1]==3:
        img=cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
    h,w,d=img.shape
    def func(i,j):
        color=img[i,j]
        grayscale=int(np.average(color[:3]))
        alpha=(255-grayscale) if grayscale < threshold*255 else 0
        img[i,j]=np.array([0,0,0,alpha])
    args=[[i,j] for i in range(0,h) for j in range(0,w)]
    for arg in tqdm(args):
        func(*arg)
    return img


def pHash(path, grid=8):
    import cv2
    import numpy as np
    src = cvImread(path, 0)
    img = cv2.resize(src, (grid,grid), cv2.COLOR_RGB2GRAY)
    avg = np.average(img) 
    # 计算哈希值,与平均值比较生成01字符串
    hashstr = ''
    for i in range(grid):
        hashstr += ''.join(map(lambda j: '0' if j< avg else '1', img[i]))
    result=int(hashstr, 2)
    hashlen=grid*grid
    maxlen=int(hashlen/4)+hashlen%4
    return f"{result:0{maxlen}x}", maxlen


def hamming_distance(str1, str2):
    if len(str1) != len(str2):
        return
    count = 0
    for i in range(len(str1)):
        if str1[i] != str2[i]:
            count += 1
    return count

def get_blank_img(width=320,height=320,color=(255,255,255)):
    import numpy as np
    img = np.zeros((height,width,3), np.uint8)
    img[:,:,0]+=color[2]
    img[:,:,1]+=color[1]
    img[:,:,2]+=color[0]
    return img

def draw_cross(image, cross_radius=10):
    import cv2
    import numpy as np
    """
    在传入的图像中绘制十字架
    :param image: 传入的需要绘制十字架的图片
    :param cross_radius: 需要绘制的十字架的半径
    :return: 返回绘制好十字架的图像
    """
    center_x = image.shape[0] // 2  # 图像的中心点x坐标
    center_y = image.shape[1] // 2
    cross_x1 = center_x - cross_radius  # 十字的左顶点
    cross_x2 = center_x + cross_radius
    cross_y1 = center_y - cross_radius  # 十字的上顶点
    cross_y2 = center_y + cross_radius
    # 使用cv2.polylines()画多条直线也可以用来画多边形
    line1 = np.array([[cross_x1, center_y], [cross_x2, center_y]], np.int32).reshape((-1, 1, 2))
    line2 = np.array([[center_x, cross_y1], [center_x, cross_y2]], np.int32).reshape((-1, 1, 2))
    # line3 = np.array([[100, 100], [300, 100]], np.int32).reshape((-1, 1, 2))
    cv2.polylines(image, pts=[line1, line2], isClosed=False, color=(255, 0, 0), thickness=2, lineType=cv2.LINE_8)
    return image

def defaultColorBank(maxColorType):
    import numpy as np
    level=2
    while level**3-level<maxColorType:
        level+=1
    stride=256//(level)
    stages=[i*stride for i in range(1,level)]+[255]
    colors=[[r,g,b] for b in stages for r in stages for g in stages if not (b==g and b==r)]
    colors=np.array(colors, dtype=np.uint8)
    return colors

def getScaleSize(originHeight, originWidth, targetHeight=None, targetWidth=None):
    h=originHeight
    w=originWidth
    if targetWidth is None and targetHeight is not None:
        targetWidth=w*(targetHeight/h)
    if targetHeight is None and targetWidth is not None:
        targetHeight=h*(targetWidth/w)
    if targetWidth is None and targetHeight is None:
        targetWidth=w
        targetHeight=h
    return targetHeight, targetWidth

def cvImread(file_path, flag=-1):
    import cv2
    import numpy as np
    cv_img = cv2.imdecode(np.fromfile(file_path,dtype=np.uint8),flag)
    return cv_img

def showImgCV2(img, height=None, width=None, title='Image', waitKey=True):
    import cv2
    h=img.shape[0]
    w=img.shape[1]
    height, width=getScaleSize(h, w, height,width)
    img = cv2.resize(img, (int(width), int(height)))
    cv2.imshow(title, img)
    if waitKey: cv2.waitKey(0)

def saveImgCV2(img, savePath='image.jpg',height=None, width=None):
    import cv2
    h=img.shape[0]
    w=img.shape[1]
    height, width=getScaleSize(h, w, height,width)
    img = cv2.resize(img, (int(width), int(height)))
    cv2.imwrite(str(savePath), img)

def generateVideo(videoPath,imgFiles,fps=None,width=None,height=None,pbar=False):
    import cv2
    videoPath=str(Path(videoPath).absolute())
    fps=4 if fps is None else int(fps)
    img0=cvImread(imgFiles[0])
    height, width=getScaleSize(img0.shape[0], img0.shape[1], height,width)
    video=cv2.VideoWriter(videoPath,cv2.VideoWriter_fourcc(*'MJPG'),fps,(width,height))
    frameNum=len(imgFiles)
    if pbar:
        filename=videoPath
        filetqdm=tqdm(total=frameNum, desc=f"Generating video {limitLenStr(filename)}")
    for file in imgFiles:
        img=cvImread(file)
        img=cv2.resize(img,(width,height))
        video.write(img)
        if pbar: filetqdm.update()
    video.release()
    return videoPath

def thumbnail_image(source, target, maxw=300, maxh=500):
    import cv2
    import numpy as np
    img=cv2.imdecode(np.fromfile(source, dtype=np.uint8), -1)
    h=img.shape[0]
    w=img.shape[1]
    scale=max(h/maxh, w/maxw)
    th=int(h/scale)
    tw=int(w/scale)
    img=cv2.resize(img, [tw,th])
    cv2.imwrite(str(target), img)
    return target