import logging as logger
import os
import tarfile

from exif import Image


def zip_file(from_path, to_path):
    parentDir = os.path.abspath(os.path.dirname(from_path) + os.path.sep + ".")
    with tarfile.open(to_path, 'w:gz') as zipFile:
        for root, dirs, files in os.walk(from_path, topdown=True):
            for name in files:
                try:
                    absPath = os.path.join(root, name)  # 文件绝对路径
                    arcname = os.path.relpath(absPath, parentDir)  # 文件相对路径
                    if not os.path.exists(absPath):
                        continue
                    zipFile.add(absPath, arcname)
                except Exception as e:
                    logger.debug(e)
                    pass


def unzip_file(from_path, to_path):
    if to_path is None:
        end = from_path.rfind('/')
        if end < 0:
            end = from_path.rfind('\\')
        to_path = from_path[0:end]
    tar = tarfile.open(from_path, 'r:gz')
    tar.extractall(to_path)
    tar.close()


def get_file_attribs(path):
    info = {}
    img_file = open(path, 'rb')
    img = Image(img_file)
    all_props = img.list_all()
    for prop in all_props:
        try:
            info[prop] = img.get(prop)
        except Exception as e:
            logger.debug(repr(e))
            continue
    img_file.close()
    return info


def set_file_attribs(path, attribs):
    try:
        img_file = open(path, 'rb')
        img = Image(img_file)
        img_file.close()
        try:
            if 'image_description' in attribs:
                img.image_description = attribs['image_description']
            new_img_file = open(path, 'wb')
            new_img_file.write(img.get_file())
            logger.info(f"文件 {path} 详情赋值成功")
        except Exception as e1:
            logger.info(f"ERROR: {repr(e1)}，文件 {path} 详情赋值失败")
    except Exception as e2:
        logger.error(f"文件 {path} 打开失败：{repr(e2)}")


if __name__ == '__main__':
    print(get_file_attribs(
        r"C:\Users\DELL-1\Downloads\image_data_publicinfo_1686470117524\full\55e2c2867a97a4c31b3cd5be15ba7717df83a7b1.jpg"))
    # set_file_attribs(
    #     r"D:\usr\local\temp_image\full\9b1ffc57ca4f097066084115542b0719554a6d36.jpg",
    #     {'image_description': "20;23;06;11"})
