# -*- coding: utf-8 -*-
import os
import shutil
import time
import zipfile

import oss2
from resource import camera_mp4
import logging

path1 = '/mnt/disk001/dcl_data_process/src/python2/pjisuv/'

logging.basicConfig(filename=path1 + 'log/camera-pjisuv.log', level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s')

key1 = 'pjisuv/'
sleep_time = 60  # 每多少秒扫描一次


def zip_jpg_files(directory):
    # 获取指定目录下的所有.jpg 文件路径
    jpg_files = [os.path.join(directory, f) for f in os.listdir(directory) if f.endswith('.jpg')]

    # 创建或覆盖同目录下的 camera.zip 压缩包
    with zipfile.ZipFile(os.path.join(directory, 'camera.zip'), 'w') as zipf:
        for file1 in jpg_files:
            zipf.write(file1, os.path.basename(file1))


def parse_to_mp4(bucket, merged_bag_object_key, merged_bag_file_path, parse_prefix_full1, local_parse_dir, data_name):
    try:
        # 1 解析
        local_mp4_dir, hz = camera_mp4.parse(merged_bag_file_path, local_parse_dir)
        logging.info("已生成图片jpg和视频mp4到目录: %s", local_mp4_dir)
        oss_mp4_key1 = parse_prefix_full1 + 'camera.mp4'
        oss_mp4_key2 = parse_prefix_full1 + 'camera_' + data_name + '_' + str(hz) + '.mp4'
        local_mp4_path = local_mp4_dir + '/camera.mp4'
        oss_zip_key = parse_prefix_full1 + 'camera_' + data_name + '_' + str(hz) + '.zip'
        local_zip_path = local_mp4_dir + '/camera.zip'
        # 2 上传 camera.mp4 文件
        bucket.put_object_from_file(oss_mp4_key1, local_mp4_path)
        bucket.put_object_from_file(oss_mp4_key2, local_mp4_path)
        logging.info("已上传图像视频到: %s", oss_mp4_key2)
        # 3 删除本地 camera.mp4
        try:
            os.remove(local_mp4_path)
        except Exception as e:
            logging.exception("临时文件删除报错: %s", str(e))
        # 4 打包图片文件并上传压缩包
        zip_jpg_files(local_mp4_dir)
        bucket.put_object_from_file(oss_zip_key, local_zip_path)
        try:
            os.remove(local_zip_path)
        except Exception as e:
            logging.exception("临时文件删除报错: %s", str(e))
        logging.info("已上传摄像头图片压缩包到: %s", oss_zip_key)
        # 5 目录
        try:
            shutil.rmtree(local_mp4_dir)
        except Exception as e:
            logging.exception("临时目录报错: %s", str(e))
    except Exception as e2:
        # 当出现异常时执行的代码
        logging.exception("生成摄像头视频报错: %s", e2)
        # 删除 data_parse 路径
        # 删除多个文件。
        for obj in oss2.ObjectIterator(bucket, prefix=parse_prefix_full1):
            bucket.delete_object(obj.key)
        # 删除 bag包
        bucket.delete_object(merged_bag_object_key)


# ------- 获取合并之后的bag包，解析出csv -------
if __name__ == '__main__':
    # 1 创建阿里云对象
    auth = oss2.Auth('n8glvFGS25MrLY7j', 'xZ2Fozoarpfw0z28FUhtg8cu0yDc5d')
    endpoint = 'oss-cn-beijing-gqzl-d01-a.ops.gqzl-cloud.com'
    bucket = oss2.Bucket(auth, endpoint, 'open-bucket')
    while True:
        try:
            logging.info("开始新一轮扫描")
            prefix_list = []
            # 2 获取已经上传完成的所有目录并分组
            for obj1 in oss2.ObjectIterator(bucket, prefix=key1):
                try:
                    local_delete_list = []
                    oss_delete_list = []
                    # 获取合并后的包
                    merged_bag_object_key = str(obj1.key)
                    if 'data_merge' in str(obj1.key) and str(obj1.key).endswith('.bag'):
                        merged_bag_object_key_split = merged_bag_object_key.split('/')
                        merged_prefix = '/'.join(merged_bag_object_key_split[:-1])
                        parse_prefix = merged_prefix.replace('data_merge', 'data_parse')
                        parse_prefix_full = merged_bag_object_key.replace('data_merge', 'data_parse').replace('.bag',
                                                                                                              '/')
                        camera_done = False
                        for obj2 in oss2.ObjectIterator(bucket, prefix=parse_prefix_full):
                            if '/camera_' in str(obj2.key) and str(obj2.key).endswith('.mp4'):
                                camera_done = True
                        if camera_done:
                            continue

                        local_merged_bag_path = path1 + 'camera/' + merged_bag_object_key
                        local_merged_dir = '/'.join(local_merged_bag_path.split('/')[:-1])
                        local_parse_dir = local_merged_dir.replace('data_merge', 'data_parse')
                        if not os.path.exists(local_merged_dir):
                            os.makedirs(local_merged_dir)
                        if not os.path.exists(local_parse_dir):
                            os.makedirs(local_parse_dir)
                        data_name = merged_bag_object_key_split[-1].split('.')[0].split('_')[0]
                        try:
                            bucket.get_object_to_file(merged_bag_object_key, local_merged_bag_path)
                            logging.info("解析bag包图像【%s】->【%s】", str(merged_bag_object_key),
                                         str(local_merged_bag_path), )
                        except Exception as e1:
                            logging.exception("bag包下载报错: %s", e1)
                        local_delete_list.append(local_merged_bag_path)
                        logging.info("生成 camera.mp4: %s" % parse_prefix_full)
                        parse_to_mp4(bucket, merged_bag_object_key, local_merged_bag_path, parse_prefix_full,
                                     local_parse_dir,
                                     data_name)
                        # 删除本地临时文件
                        if len(local_delete_list) > 0:
                            for local_delete in local_delete_list:
                                try:
                                    os.remove(local_delete)
                                except Exception as e:
                                    logging.exception("临时文件删除报错: %s", str(e))
                except Exception as e:
                    logging.exception("局部异常处理: %s", str(e))
            time.sleep(sleep_time)
        except Exception as e:
            logging.exception("全局异常处理: %s", str(e))
